Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
PublicationFieldValidator
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
5 / 5
7
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getValidationRules
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 validate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 makeDynamicRules
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 makeValidator
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Hyde\Publications\Actions;
6
7use Hyde\Publications\Concerns\PublicationFieldTypes;
8use Hyde\Publications\Models\PublicationFieldDefinition;
9use Hyde\Publications\Models\PublicationType;
10use Hyde\Publications\Publications;
11use Illuminate\Contracts\Validation\Validator;
12
13use function array_merge;
14use function validator;
15
16/**
17 * @see \Hyde\Publications\Testing\Feature\PublicationFieldValidatorTest
18 */
19class PublicationFieldValidator
20{
21    protected PublicationType $publicationType;
22    protected PublicationFieldDefinition $fieldDefinition;
23
24    public function __construct(PublicationType $publicationType, PublicationFieldDefinition $fieldDefinition)
25    {
26        $this->publicationType = $publicationType;
27        $this->fieldDefinition = $fieldDefinition;
28    }
29
30    public function getValidationRules(): array
31    {
32        return array_merge(
33            $this->fieldDefinition->getRules(),
34            $this->makeDynamicRules()
35        );
36    }
37
38    /** @throws \Illuminate\Validation\ValidationException */
39    public function validate(mixed $input = null): array
40    {
41        return $this->makeValidator($input, $this->getValidationRules())->validate();
42    }
43
44    protected function makeDynamicRules(): array
45    {
46        if ($this->fieldDefinition->type == PublicationFieldTypes::Media) {
47            $mediaFiles = Publications::getMediaForType($this->publicationType);
48            $valueList = $mediaFiles->implode(',');
49
50            return ["in:$valueList"];
51        }
52
53        if ($this->fieldDefinition->type == PublicationFieldTypes::Tag) {
54            $tagValues = Publications::getPublicationTags() ?? [];
55            $valueList = implode(',', $tagValues);
56
57            return ["in:$valueList"];
58        }
59
60        return [];
61    }
62
63    protected function makeValidator(mixed $input, array $rules): Validator
64    {
65        return validator(
66            [$this->fieldDefinition->name => $input],
67            [$this->fieldDefinition->name => $rules]
68        );
69    }
70}