3 namespace Tests\Exports;
5 use BookStack\Exports\Import;
6 use Illuminate\Http\UploadedFile;
7 use Illuminate\Testing\TestResponse;
12 public static function importFromData(array $importData, array $zipData, array $files = []): Import
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';
22 $import = Import::factory()->create($importData);
23 $zip = static::zipUploadFromData($zipData, $files);
24 $targetPath = storage_path($import->path);
25 $targetDir = dirname($targetPath);
27 if (!file_exists($targetDir)) {
31 rename($zip->getRealPath(), $targetPath);
36 public static function deleteZipForImport(Import $import): void
38 $path = storage_path($import->path);
39 if (file_exists($path)) {
44 public static function zipUploadFromData(array $data, array $files = []): UploadedFile
46 $zipFile = tempnam(sys_get_temp_dir(), 'bstest-');
48 $zip = new ZipArchive();
49 $zip->open($zipFile, ZipArchive::CREATE);
50 $zip->addFromString('data.json', json_encode($data));
52 foreach ($files as $name => $file) {
53 $zip->addFile($file, "files/$name");
58 return new UploadedFile($zipFile, 'upload.zip', 'application/zip', null, true);
61 public static function extractFromZipResponse(TestResponse $response): ZipResultData
63 $zipData = $response->streamedContent();
64 $zipFile = tempnam(sys_get_temp_dir(), 'bstest-');
66 file_put_contents($zipFile, $zipData);
67 $extractDir = tempnam(sys_get_temp_dir(), 'bstestextracted-');
68 if (file_exists($extractDir)) {
73 $zip = new ZipArchive();
74 $zip->open($zipFile, ZipArchive::RDONLY);
75 $zip->extractTo($extractDir);
77 $dataJson = file_get_contents($extractDir . DIRECTORY_SEPARATOR . "data.json");
78 $data = json_decode($dataJson, true);
80 return new ZipResultData(