]> BookStack Code Mirror - bookstack/blob - tests/Exports/ZipTestHelper.php
Lexical: Updated WYSIWYG editor status from alpha to beta
[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         $targetPath = storage_path($import->path);
24         $targetDir = dirname($targetPath);
25
26         if (!file_exists($targetDir)) {
27             mkdir($targetDir);
28         }
29
30         rename($zip->getRealPath(), $targetPath);
31
32         return $import;
33     }
34
35     public static function deleteZipForImport(Import $import): void
36     {
37         $path = storage_path($import->path);
38         if (file_exists($path)) {
39             unlink($path);
40         }
41     }
42
43     public static function zipUploadFromData(array $data, array $files = []): UploadedFile
44     {
45         $zipFile = tempnam(sys_get_temp_dir(), 'bstest-');
46
47         $zip = new ZipArchive();
48         $zip->open($zipFile, ZipArchive::CREATE);
49         $zip->addFromString('data.json', json_encode($data));
50
51         foreach ($files as $name => $file) {
52             $zip->addFile($file, "files/$name");
53         }
54
55         $zip->close();
56
57         return new UploadedFile($zipFile, 'upload.zip', 'application/zip', null, true);
58     }
59 }