]> BookStack Code Mirror - system-cli/blob - src/Services/BackupZip.php
Bumped version
[system-cli] / src / Services / BackupZip.php
1 <?php declare(strict_types=1);
2
3 namespace Cli\Services;
4
5 use ZipArchive;
6
7 class BackupZip
8 {
9     protected ZipArchive $zip;
10     public function __construct(
11         protected string $filePath
12     ) {
13         $this->zip = new ZipArchive();
14         $status = $this->zip->open($this->filePath);
15
16         if (!file_exists($this->filePath) || $status !== true) {
17             throw new \Exception("Could not open file [{$this->filePath}] as ZIP");
18         }
19     }
20
21     /**
22      * @return array<string, array{desc: string, exists: bool}>
23      */
24     public function getContentsOverview(): array
25     {
26         return [
27             'env' => [
28                 'desc' => '.env Config File',
29                 'exists' => boolval($this->zip->statName('.env')),
30             ],
31             'themes' => [
32                 'desc' => 'Themes Folder',
33                 'exists' => $this->hasFolder('themes/'),
34             ],
35             'public/uploads' => [
36                 'desc' => 'Public File Uploads',
37                 'exists' => $this->hasFolder('public/uploads/'),
38             ],
39             'storage/uploads' => [
40                 'desc' => 'Private File Uploads',
41                 'exists' => $this->hasFolder('storage/uploads/'),
42             ],
43             'db' => [
44                 'desc' => 'Database Dump',
45                 'exists' => boolval($this->zip->statName('db.sql')),
46             ],
47         ];
48     }
49
50     public function extractInto(string $directoryPath): void
51     {
52         $result = $this->zip->extractTo($directoryPath);
53         if (!$result) {
54             throw new \Exception("Failed extraction of ZIP into [{$directoryPath}].");
55         }
56     }
57
58     protected function hasFolder($folderPath): bool
59     {
60         for ($i = 0; $i < $this->zip->numFiles; $i++) {
61             $filePath = $this->zip->getNameIndex($i);
62             if (str_starts_with($filePath, $folderPath)) {
63                 return true;
64             }
65         }
66         return false;
67     }
68 }