Passed
Pull Request — master (#332)
by Dmitriy
03:02
created

Validator::normalizeRule()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.675

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 21
ccs 7
cts 10
cp 0.7
rs 9.6111
cc 5
nc 4
nop 1
crap 5.675
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\Validator\DataSet\ArrayDataSet;
15
use Yiisoft\Validator\DataSet\ObjectDataSet;
16
use Yiisoft\Validator\DataSet\MixedDataSet;
17
use Yiisoft\Validator\Rule\Callback;
18
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
19
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
20
21
use function is_array;
22
use function is_callable;
23
use function is_int;
24
use function is_object;
25
26
/**
27
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
28
 */
29
final class Validator implements ValidatorInterface
30
{
31
    use PreValidateTrait;
32
33
    /**
34
     * @var callable
35
     */
36
    private $defaultSkipOnEmptyCallback;
37
38 661
    public function __construct(
39
        private RuleHandlerResolverInterface $ruleHandlerResolver,
40
        /**
41
         * @var int What visibility levels to use when reading rules from the class specified in `$rules` argument in
42
         * {@see validate()} method.
43
         */
44
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
45
        | ReflectionProperty::IS_PROTECTED
46
        | ReflectionProperty::IS_PUBLIC,
47
48
        /**
49
         * @var bool|callable|null
50
         */
51
        $defaultSkipOnEmpty = null,
52
    ) {
53 661
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
54
    }
55
56
    /**
57
     * @param DataSetInterface|mixed|RulesProviderInterface $data
58
     * @param class-string|iterable<Closure|Closure[]|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[]>|RulesProviderInterface|null.
Loading history...
59
     *
60
     * @throws ContainerExceptionInterface
61
     * @throws NotFoundExceptionInterface
62
     */
63 132
    public function validate(mixed $data, iterable|object|string|null $rules = null): Result
64
    {
65 132
        $data = $this->normalizeDataSet($data);
66 132
        if ($rules === null && $data instanceof RulesProviderInterface) {
67 26
            $rules = $data->getRules();
68 110
        } elseif ($rules instanceof RulesProviderInterface) {
69 2
            $rules = $rules->getRules();
70 108
        } elseif (!$rules instanceof Traversable && !is_array($rules) && $rules !== null) {
71
            $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

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