Passed
Push — master ( 27e454...aa5826 )
by
unknown
04:33 queued 01:58
created

Validator::normalizeRules()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
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 643
    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 643
        $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 114
    public function validate(
64
        mixed $data,
65
        iterable|object|string|null $rules = null
66
    ): Result {
67 114
        $data = $this->normalizeDataSet($data);
68 114
        if ($rules === null && $data instanceof RulesProviderInterface) {
69 25
            $rules = $data->getRules();
70 93
        } elseif ($rules instanceof RulesProviderInterface) {
71 2
            $rules = $rules->getRules();
72 91
        } elseif (!$rules instanceof Traversable && !is_array($rules) && $rules !== null) {
73
            $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

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