]> BookStack Code Mirror - bookstack/blob - app/Exports/ZipExports/ZipValidationHelper.php
Customization: Added parent tag classes
[bookstack] / app / Exports / ZipExports / ZipValidationHelper.php
1 <?php
2
3 namespace BookStack\Exports\ZipExports;
4
5 use BookStack\Exports\ZipExports\Models\ZipExportModel;
6 use Illuminate\Validation\Factory;
7
8 class ZipValidationHelper
9 {
10     protected Factory $validationFactory;
11
12     /**
13      * Local store of validated IDs (in format "<type>:<id>". Example: "book:2")
14      * which we can use to check uniqueness.
15      * @var array<string, bool>
16      */
17     protected array $validatedIds = [];
18
19     public function __construct(
20         public ZipExportReader $zipReader,
21     ) {
22         $this->validationFactory = app(Factory::class);
23     }
24
25     public function validateData(array $data, array $rules): array
26     {
27         $messages = $this->validationFactory->make($data, $rules)->errors()->messages();
28
29         foreach ($messages as $key => $message) {
30             $messages[$key] = implode("\n", $message);
31         }
32
33         return $messages;
34     }
35
36     public function fileReferenceRule(array $acceptedMimes = []): ZipFileReferenceRule
37     {
38         return new ZipFileReferenceRule($this, $acceptedMimes);
39     }
40
41     public function uniqueIdRule(string $type): ZipUniqueIdRule
42     {
43         return new ZipUniqueIdRule($this, $type);
44     }
45
46     public function hasIdBeenUsed(string $type, mixed $id): bool
47     {
48         $key = $type . ':' . $id;
49         if (isset($this->validatedIds[$key])) {
50             return true;
51         }
52
53         $this->validatedIds[$key] = true;
54
55         return false;
56     }
57
58     /**
59      * Validate an array of relation data arrays that are expected
60      * to be for the given ZipExportModel.
61      * @param class-string<ZipExportModel> $model
62      */
63     public function validateRelations(array $relations, string $model): array
64     {
65         $results = [];
66
67         foreach ($relations as $key => $relationData) {
68             if (is_array($relationData)) {
69                 $results[$key] = $model::validate($this, $relationData);
70             } else {
71                 $results[$key] = [trans('validation.zip_model_expected', ['type' => gettype($relationData)])];
72             }
73         }
74
75         return $results;
76     }
77 }