]> BookStack Code Mirror - bookstack/blob - tests/Exports/ZipTestHelper.php
ZIP Imports: Added API examples, finished testing
[bookstack] / tests / Exports / ZipTestHelper.php
1 <?php
2
3 namespace Tests\Exports;
4
5 use BookStack\Exports\Import;
6 use Illuminate\Http\UploadedFile;
7 use Illuminate\Testing\TestResponse;
8 use ZipArchive;
9
10 class ZipTestHelper
11 {
12     public static function importFromData(array $importData, array $zipData, array $files = []): Import
13     {
14         if (isset($zipData['book'])) {
15             $importData['type'] = 'book';
16         } else if (isset($zipData['chapter'])) {
17             $importData['type'] = 'chapter';
18         } else if (isset($zipData['page'])) {
19             $importData['type'] = 'page';
20         }
21
22         $import = Import::factory()->create($importData);
23         $zip = static::zipUploadFromData($zipData, $files);
24         $targetPath = storage_path($import->path);
25         $targetDir = dirname($targetPath);
26
27         if (!file_exists($targetDir)) {
28             mkdir($targetDir);
29         }
30
31         rename($zip->getRealPath(), $targetPath);
32
33         return $import;
34     }
35
36     public static function deleteZipForImport(Import $import): void
37     {
38         $path = storage_path($import->path);
39         if (file_exists($path)) {
40             unlink($path);
41         }
42     }
43
44     public static function zipUploadFromData(array $data, array $files = []): UploadedFile
45     {
46         $zipFile = tempnam(sys_get_temp_dir(), 'bstest-');
47
48         $zip = new ZipArchive();
49         $zip->open($zipFile, ZipArchive::CREATE);
50         $zip->addFromString('data.json', json_encode($data));
51
52         foreach ($files as $name => $file) {
53             $zip->addFile($file, "files/$name");
54         }
55
56         $zip->close();
57
58         return new UploadedFile($zipFile, 'upload.zip', 'application/zip', null, true);
59     }
60
61     public static function extractFromZipResponse(TestResponse $response): ZipResultData
62     {
63         $zipData = $response->streamedContent();
64         $zipFile = tempnam(sys_get_temp_dir(), 'bstest-');
65
66         file_put_contents($zipFile, $zipData);
67         $extractDir = tempnam(sys_get_temp_dir(), 'bstestextracted-');
68         if (file_exists($extractDir)) {
69             unlink($extractDir);
70         }
71         mkdir($extractDir);
72
73         $zip = new ZipArchive();
74         $zip->open($zipFile, ZipArchive::RDONLY);
75         $zip->extractTo($extractDir);
76
77         $dataJson = file_get_contents($extractDir . DIRECTORY_SEPARATOR . "data.json");
78         $data = json_decode($dataJson, true);
79
80         return new ZipResultData(
81             $zipFile,
82             $extractDir,
83             $data,
84         );
85     }
86 }