]> BookStack Code Mirror - bookstack/blob - app/Exports/ZipExports/Models/ZipExportAttachment.php
1dbdc7333e823de3e4d9189f22a869ced2c31cb6
[bookstack] / app / Exports / ZipExports / Models / ZipExportAttachment.php
1 <?php
2
3 namespace BookStack\Exports\ZipExports\Models;
4
5 use BookStack\Exports\ZipExports\ZipExportFiles;
6 use BookStack\Exports\ZipExports\ZipValidationHelper;
7 use BookStack\Uploads\Attachment;
8
9 class ZipExportAttachment extends ZipExportModel
10 {
11     public ?int $id = null;
12     public string $name;
13     public ?int $order = null;
14     public ?string $link = null;
15     public ?string $file = null;
16
17     public function metadataOnly(): void
18     {
19         $this->order = $this->link = $this->file = null;
20     }
21
22     public static function fromModel(Attachment $model, ZipExportFiles $files): self
23     {
24         $instance = new self();
25         $instance->id = $model->id;
26         $instance->name = $model->name;
27         $instance->order = $model->order;
28
29         if ($model->external) {
30             $instance->link = $model->path;
31         } else {
32             $instance->file = $files->referenceForAttachment($model);
33         }
34
35         return $instance;
36     }
37
38     public static function fromModelArray(array $attachmentArray, ZipExportFiles $files): array
39     {
40         return array_values(array_map(function (Attachment $attachment) use ($files) {
41             return self::fromModel($attachment, $files);
42         }, $attachmentArray));
43     }
44
45     public static function validate(ZipValidationHelper $context, array $data): array
46     {
47         $rules = [
48             'id'    => ['nullable', 'int'],
49             'name'  => ['required', 'string', 'min:1'],
50             'order' => ['nullable', 'integer'],
51             'link'  => ['required_without:file', 'nullable', 'string'],
52             'file'  => ['required_without:link', 'nullable', 'string', $context->fileReferenceRule()],
53         ];
54
55         return $context->validateData($data, $rules);
56     }
57
58     public static function fromArray(array $data): self
59     {
60         $model = new self();
61
62         $model->id = $data['id'] ?? null;
63         $model->name = $data['name'];
64         $model->order = isset($data['order']) ? intval($data['order']) : null;
65         $model->link = $data['link'] ?? null;
66         $model->file = $data['file'] ?? null;
67
68         return $model;
69     }
70 }