Passed
Push — master ( b77ded...9fd61f )
by
unknown
02:40
created

Validator   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 175
Duplicated Lines 0 %

Test Coverage

Coverage 93.24%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 33
eloc 74
c 3
b 0
f 0
dl 0
loc 175
ccs 69
cts 74
cp 0.9324
rs 9.76

6 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeRule() 0 21 5
A normalizeRules() 0 4 2
A __construct() 0 17 1
D validate() 0 57 15
A validateInternal() 0 25 6
A normalizeDataSet() 0 16 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Closure;
8
use InvalidArgumentException;
9
use JetBrains\PhpStorm\Pure;
10
use Psr\Container\ContainerExceptionInterface;
11
use Psr\Container\NotFoundExceptionInterface;
12
use ReflectionProperty;
13
use Traversable;
14
use Yiisoft\Translator\TranslatorInterface;
15
use Yiisoft\Validator\DataSet\ArrayDataSet;
16
use Yiisoft\Validator\DataSet\ObjectDataSet;
17
use Yiisoft\Validator\DataSet\MixedDataSet;
18
use Yiisoft\Validator\Rule\Callback;
19
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
20
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
21
22
use function is_array;
23
use function is_callable;
24
use function is_int;
25
use function is_object;
26
27
/**
28
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
29
 */
30
final class Validator implements ValidatorInterface
31
{
32
    use PreValidateTrait;
33
34
    /**
35
     * @var callable
36
     */
37
    private $defaultSkipOnEmptyCallback;
38
39 661
    public function __construct(
40
        private RuleHandlerResolverInterface $ruleHandlerResolver,
41
        private TranslatorInterface $translator,
42
        /**
43
         * @var int What visibility levels to use when reading rules from the class specified in `$rules` argument in
44
         * {@see validate()} method.
45
         */
46
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
47
        | ReflectionProperty::IS_PROTECTED
48
        | ReflectionProperty::IS_PUBLIC,
49
50
        /**
51
         * @var bool|callable|null
52
         */
53
        $defaultSkipOnEmpty = null,
54
    ) {
55 661
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
56
    }
57
58
    /**
59
     * @param DataSetInterface|mixed|RulesProviderInterface $data
60
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RuleInterface|RulesProviderInterface|null $rules
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string|iterable<Cl...sProviderInterface|null at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RuleInterface|RulesProviderInterface|null.
Loading history...
61
     *
62
     * @throws ContainerExceptionInterface
63
     * @throws NotFoundExceptionInterface
64
     */
65 681
    public function validate(mixed $data, iterable|object|string|null $rules = null): Result
66
    {
67 681
        $data = $this->normalizeDataSet($data);
68 681
        if ($rules === null && $data instanceof RulesProviderInterface) {
69 26
            $rules = $data->getRules();
70 659
        } elseif ($rules instanceof RulesProviderInterface) {
71 2
            $rules = $rules->getRules();
72 657
        } elseif ($rules instanceof RuleInterface) {
73 1
            $rules = [$rules];
74 656
        } elseif (!$rules instanceof Traversable && !is_array($rules) && $rules !== null) {
75
            $rules = (new AttributesRulesProvider($rules, $this->rulesPropertyVisibility))->getRules();
0 ignored issues
show
Bug introduced by
It seems like $rules can also be of type iterable; however, parameter $source of Yiisoft\Validator\RulesP...Provider::__construct() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

75
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $rules, $this->rulesPropertyVisibility))->getRules();
Loading history...
76
        }
77
78 681
        $compoundResult = new Result();
79 681
        $context = new ValidationContext($this, $data);
80 681
        $results = [];
81
82 681
        foreach ($rules ?? [] as $attribute => $attributeRules) {
83 670
            $result = new Result();
84
85 670
            if (!is_iterable($attributeRules)) {
86 596
                $attributeRules = [$attributeRules];
87
            }
88
89 670
            $attributeRules = $this->normalizeRules($attributeRules);
90
91 670
            if (is_int($attribute)) {
92 581
                $validatedData = $data->getData();
93
            } else {
94 93
                $validatedData = $data->getAttributeValue($attribute);
95 93
                $context = $context->withAttribute($attribute);
96
            }
97
98 670
            $tempResult = $this->validateInternal($validatedData, $attributeRules, $context);
99
100 642
            foreach ($tempResult->getErrors() as $error) {
101 374
                $result->addError($error->getMessage(), $error->getParameters(), $error->getValuePath());
102
            }
103
104 642
            $results[] = $result;
105
        }
106
107 653
        foreach ($results as $result) {
108 642
            foreach ($result->getErrors() as $error) {
109 374
                $compoundResult->addError(
110 374
                    $this->translator->translate($error->getMessage(), $error->getParameters()),
111 374
                    $error->getParameters(),
112 374
                    $error->getValuePath()
113
                );
114
            }
115
        }
116
117 653
        if ($data instanceof PostValidationHookInterface) {
118
            $data->processValidationResult($compoundResult);
119
        }
120
121 653
        return $compoundResult;
122
    }
123
124 681
    #[Pure]
125
    private function normalizeDataSet($data): DataSetInterface
126
    {
127 681
        if ($data instanceof DataSetInterface) {
128 68
            return $data;
129
        }
130
131 618
        if (is_object($data)) {
132 37
            return new ObjectDataSet($data);
133
        }
134
135 585
        if (is_array($data)) {
136 104
            return new ArrayDataSet($data);
137
        }
138
139 504
        return new MixedDataSet($data);
140
    }
141
142
    /**
143
     * @param iterable<Closure|Closure[]|RuleInterface|RuleInterface[]> $rules
144
     */
145 670
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
146
    {
147 670
        $compoundResult = new Result();
148 670
        foreach ($rules as $rule) {
149 670
            if ($this->preValidate($value, $context, $rule)) {
150 27
                continue;
151
            }
152
153 664
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
154 662
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
155 636
            if ($ruleResult->isValid()) {
156 285
                continue;
157
            }
158
159 374
            $context->setParameter($this->parameterPreviousRulesErrored, true);
160
161 374
            foreach ($ruleResult->getErrors() as $error) {
162 374
                $valuePath = $error->getValuePath();
163 374
                if ($context->getAttribute() !== null) {
164 66
                    $valuePath = [$context->getAttribute(), ...$valuePath];
165
                }
166 374
                $compoundResult->addError($error->getMessage(), $error->getParameters(), $valuePath);
167
            }
168
        }
169 642
        return $compoundResult;
170
    }
171
172
    /**
173
     * @param array $rules
174
     *
175
     * @return iterable<RuleInterface>
176
     */
177 670
    private function normalizeRules(iterable $rules): iterable
178
    {
179 670
        foreach ($rules as $rule) {
180 670
            yield $this->normalizeRule($rule);
181
        }
182
    }
183
184 670
    private function normalizeRule($rule): RuleInterface
185
    {
186 670
        if (is_callable($rule)) {
187 3
            return new Callback($rule);
188
        }
189
190 670
        if (!$rule instanceof RuleInterface) {
191
            throw new InvalidArgumentException(
192
                sprintf(
193
                    'Rule should be either an instance of %s or a callable, %s given.',
194
                    RuleInterface::class,
195
                    get_debug_type($rule)
196
                )
197
            );
198
        }
199
200 670
        if ($rule instanceof SkipOnEmptyInterface && $rule->getSkipOnEmpty() === null) {
201 614
            $rule = $rule->skipOnEmpty($this->defaultSkipOnEmptyCallback);
202
        }
203
204 670
        return $rule;
205
    }
206
}
207