Passed
Pull Request — master (#320)
by Dmitriy
04:35 queued 01:44
created

Validator::normalizeDataSet()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

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

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

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