]> BookStack Code Mirror - bookstack/blob - app/Exports/ZipExports/ZipValidationHelper.php
8c285deaf5dd802fd42a8d16f87924d905ded3cf
[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 use ZipArchive;
8
9 class ZipValidationHelper
10 {
11     protected Factory $validationFactory;
12
13     public function __construct(
14         protected ZipArchive $zip,
15     ) {
16         $this->validationFactory = app(Factory::class);
17     }
18
19     public function validateData(array $data, array $rules): array
20     {
21         $messages = $this->validationFactory->make($data, $rules)->errors()->messages();
22
23         foreach ($messages as $key => $message) {
24             $messages[$key] = implode("\n", $message);
25         }
26
27         return $messages;
28     }
29
30     public function zipFileExists(string $name): bool
31     {
32         return $this->zip->statName("files/{$name}") !== false;
33     }
34
35     public function fileReferenceRule(): ZipFileReferenceRule
36     {
37         return new ZipFileReferenceRule($this);
38     }
39
40     /**
41      * Validate an array of relation data arrays that are expected
42      * to be for the given ZipExportModel.
43      * @param class-string<ZipExportModel> $model
44      */
45     public function validateRelations(array $relations, string $model): array
46     {
47         $results = [];
48
49         foreach ($relations as $key => $relationData) {
50             if (is_array($relationData)) {
51                 $results[$key] = $model::validate($this, $relationData);
52             } else {
53                 $results[$key] = [trans('validation.zip_model_expected', ['type' => gettype($relationData)])];
54             }
55         }
56
57         return $results;
58     }
59 }