]> BookStack Code Mirror - bookstack/blob - app/Exports/ZipExports/Models/ZipExportChapter.php
ZIP Exports: Got zip format validation functionally complete
[bookstack] / app / Exports / ZipExports / Models / ZipExportChapter.php
1 <?php
2
3 namespace BookStack\Exports\ZipExports\Models;
4
5 use BookStack\Entities\Models\Chapter;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Exports\ZipExports\ZipExportFiles;
8 use BookStack\Exports\ZipExports\ZipValidationHelper;
9
10 class ZipExportChapter extends ZipExportModel
11 {
12     public ?int $id = null;
13     public string $name;
14     public ?string $description_html = null;
15     public ?int $priority = null;
16     /** @var ZipExportPage[] */
17     public array $pages = [];
18     /** @var ZipExportTag[] */
19     public array $tags = [];
20
21     public static function fromModel(Chapter $model, ZipExportFiles $files): self
22     {
23         $instance = new self();
24         $instance->id = $model->id;
25         $instance->name = $model->name;
26         $instance->description_html = $model->descriptionHtml();
27         $instance->priority = $model->priority;
28         $instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
29
30         $pages = $model->getVisiblePages()->filter(fn (Page $page) => !$page->draft)->all();
31         $instance->pages = ZipExportPage::fromModelArray($pages, $files);
32
33         return $instance;
34     }
35
36     /**
37      * @param Chapter[] $chapterArray
38      * @return self[]
39      */
40     public static function fromModelArray(array $chapterArray, ZipExportFiles $files): array
41     {
42         return array_values(array_map(function (Chapter $chapter) use ($files) {
43             return self::fromModel($chapter, $files);
44         }, $chapterArray));
45     }
46
47     public static function validate(ZipValidationHelper $context, array $data): array
48     {
49         $rules = [
50             'id'    => ['nullable', 'int'],
51             'name'  => ['required', 'string', 'min:1'],
52             'description_html' => ['nullable', 'string'],
53             'priority' => ['nullable', 'int'],
54             'tags' => ['array'],
55             'pages' => ['array'],
56         ];
57
58         $errors = $context->validateData($data, $rules);
59         $errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
60         $errors['pages'] = $context->validateRelations($data['pages'] ?? [], ZipExportPage::class);
61
62         return $errors;
63     }
64 }