]> BookStack Code Mirror - bookstack/blob - app/Exports/Import.php
ZIP Imports: Added API examples, finished testing
[bookstack] / app / Exports / Import.php
1 <?php
2
3 namespace BookStack\Exports;
4
5 use BookStack\Activity\Models\Loggable;
6 use BookStack\Exports\ZipExports\Models\ZipExportBook;
7 use BookStack\Exports\ZipExports\Models\ZipExportChapter;
8 use BookStack\Exports\ZipExports\Models\ZipExportPage;
9 use BookStack\Users\Models\User;
10 use Carbon\Carbon;
11 use Illuminate\Database\Eloquent\Factories\HasFactory;
12 use Illuminate\Database\Eloquent\Model;
13 use Illuminate\Database\Eloquent\Relations\BelongsTo;
14
15 /**
16  * @property int $id
17  * @property string $path
18  * @property string $name
19  * @property int $size - ZIP size in bytes
20  * @property string $type
21  * @property string $metadata
22  * @property int $created_by
23  * @property Carbon $created_at
24  * @property Carbon $updated_at
25  * @property User $createdBy
26  */
27 class Import extends Model implements Loggable
28 {
29     use HasFactory;
30
31     protected $hidden = ['metadata'];
32
33     public function getSizeString(): string
34     {
35         $mb = round($this->size / 1000000, 2);
36         return "{$mb} MB";
37     }
38
39     /**
40      * Get the URL to view/continue this import.
41      */
42     public function getUrl(string $path = ''): string
43     {
44         $path = ltrim($path, '/');
45         return url("/import/{$this->id}" . ($path ? '/' . $path : ''));
46     }
47
48     public function logDescriptor(): string
49     {
50         return "({$this->id}) {$this->name}";
51     }
52
53     public function createdBy(): BelongsTo
54     {
55         return $this->belongsTo(User::class, 'created_by');
56     }
57
58     public function decodeMetadata(): ZipExportBook|ZipExportChapter|ZipExportPage|null
59     {
60         $metadataArray = json_decode($this->metadata, true);
61         return match ($this->type) {
62             'book' => ZipExportBook::fromArray($metadataArray),
63             'chapter' => ZipExportChapter::fromArray($metadataArray),
64             'page' => ZipExportPage::fromArray($metadataArray),
65             default => null,
66         };
67     }
68 }