3 namespace BookStack\Exports\ZipExports;
5 use BookStack\Exceptions\ZipExportException;
6 use BookStack\Exports\ZipExports\Models\ZipExportBook;
7 use BookStack\Exports\ZipExports\Models\ZipExportChapter;
8 use BookStack\Exports\ZipExports\Models\ZipExportModel;
9 use BookStack\Exports\ZipExports\Models\ZipExportPage;
14 protected ZipArchive $zip;
15 protected bool $open = false;
17 public function __construct(
18 protected string $zipPath,
20 $this->zip = new ZipArchive();
24 * @throws ZipExportException
26 protected function open(): void
32 // Validate file exists
33 if (!file_exists($this->zipPath) || !is_readable($this->zipPath)) {
34 throw new ZipExportException(trans('errors.import_zip_cant_read'));
37 // Validate file is valid zip
38 $opened = $this->zip->open($this->zipPath, ZipArchive::RDONLY);
39 if ($opened !== true) {
40 throw new ZipExportException(trans('errors.import_zip_cant_read'));
46 public function close(): void
55 * @throws ZipExportException
57 public function readData(): array
61 // Validate json data exists, including metadata
62 $jsonData = $this->zip->getFromName('data.json') ?: '';
63 $importData = json_decode($jsonData, true);
65 throw new ZipExportException(trans('errors.import_zip_cant_decode_data'));
71 public function fileExists(string $fileName): bool
73 return $this->zip->statName("files/{$fileName}") !== false;
77 * @throws ZipExportException
79 public function decodeDataToExportModel(): ZipExportBook|ZipExportChapter|ZipExportPage
81 $data = $this->readData();
82 if (isset($data['book'])) {
83 return ZipExportBook::fromArray($data['book']);
84 } else if (isset($data['chapter'])) {
85 return ZipExportChapter::fromArray($data['chapter']);
86 } else if (isset($data['page'])) {
87 return ZipExportPage::fromArray($data['page']);
90 throw new ZipExportException("Could not identify content in ZIP file data.");