]> BookStack Code Mirror - bookstack/blob - tests/Exports/ZipTestHelper.php
ZIP Imports: Started testing core import logic
[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 ZipArchive;
8
9 class ZipTestHelper
10 {
11     public static function importFromData(array $importData, array $zipData, array $files = []): Import
12     {
13         if (isset($zipData['book'])) {
14             $importData['type'] = 'book';
15         } else if (isset($zipData['chapter'])) {
16             $importData['type'] = 'chapter';
17         } else if (isset($zipData['page'])) {
18             $importData['type'] = 'page';
19         }
20
21         $import = Import::factory()->create($importData);
22         $zip = static::zipUploadFromData($zipData, $files);
23         rename($zip->getRealPath(), storage_path($import->path));
24
25         return $import;
26     }
27
28     public static function deleteZipForImport(Import $import): void
29     {
30         $path = storage_path($import->path);
31         if (file_exists($path)) {
32             unlink($path);
33         }
34     }
35
36     public static function zipUploadFromData(array $data, array $files = []): UploadedFile
37     {
38         $zipFile = tempnam(sys_get_temp_dir(), 'bstest-');
39
40         $zip = new ZipArchive();
41         $zip->open($zipFile, ZipArchive::CREATE);
42         $zip->addFromString('data.json', json_encode($data));
43
44         foreach ($files as $name => $file) {
45             $zip->addFile($file, "files/$name");
46         }
47
48         $zip->close();
49
50         return new UploadedFile($zipFile, 'upload.zip', 'application/zip', null, true);
51     }
52 }