Passed
Push — master ( 55aa31...45f0f1 )
by Alexander
13:22 queued 10:36
created

Validator::validateInternal()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 25
ccs 16
cts 16
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 6
nop 3
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use InvalidArgumentException;
8
use JetBrains\PhpStorm\Pure;
9
use ReflectionException;
10
use ReflectionProperty;
11
use Traversable;
12
use Yiisoft\Translator\TranslatorInterface;
13
use Yiisoft\Validator\DataSet\ArrayDataSet;
14
use Yiisoft\Validator\DataSet\ObjectDataSet;
15
use Yiisoft\Validator\DataSet\SingleValueDataSet;
16
use Yiisoft\Validator\Rule\Callback;
17
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
18
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
19
20
use function is_array;
21
use function is_callable;
22
use function is_int;
23
use function is_object;
24
use function is_string;
25
26
/**
27
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
28
 *
29
 * @psalm-import-type RulesType from ValidatorInterface
30
 */
31
final class Validator implements ValidatorInterface
32
{
33
    use PreValidateTrait;
34
35
    /**
36
     * @var callable
37
     */
38
    private $defaultSkipOnEmptyCallback;
39
40 695
    public function __construct(
41
        private RuleHandlerResolverInterface $ruleHandlerResolver,
42
        private TranslatorInterface $translator,
43
        /**
44
         * @var int What visibility levels to use when reading rules from the class specified in `$rules` argument in
45
         * {@see validate()} method.
46
         */
47
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
48
        | ReflectionProperty::IS_PROTECTED
49
        | ReflectionProperty::IS_PUBLIC,
50
        bool|callable|null $defaultSkipOnEmpty = null,
51
    ) {
52 695
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
53
    }
54
55
    /**
56
     * @param DataSetInterface|mixed|RulesProviderInterface $data
57
     * @psalm-param RulesType $rules
58
     *
59
     * @throws ReflectionException
60
     */
61 715
    public function validate(mixed $data, iterable|object|string|null $rules = null): Result
62
    {
63 715
        $data = $this->normalizeDataSet($data);
64 715
        if ($rules === null && $data instanceof RulesProviderInterface) {
65 27
            $rules = $data->getRules();
66 692
        } elseif ($rules instanceof RulesProviderInterface) {
67 2
            $rules = $rules->getRules();
68 690
        } elseif ($rules instanceof RuleInterface) {
69 1
            $rules = [$rules];
70 689
        } elseif (is_string($rules) || (is_object($rules) && !$rules instanceof Traversable)) {
71
            $rules = (new AttributesRulesProvider($rules, $this->rulesPropertyVisibility))->getRules();
72
        }
73
74 715
        $compoundResult = new Result();
75 715
        $context = new ValidationContext($this, $data);
76 715
        $results = [];
77
78
        /**
79
         * @var mixed $attribute
80
         * @var mixed $attributeRules
81
         */
82 715
        foreach ($rules ?? [] as $attribute => $attributeRules) {
83 704
            $result = new Result();
84
85 704
            if (!is_iterable($attributeRules)) {
86 629
                $attributeRules = [$attributeRules];
87
            }
88
89 704
            $attributeRules = $this->normalizeRules($attributeRules);
90
91 704
            if (is_int($attribute)) {
92
                /** @psalm-suppress MixedAssignment */
93 613
                $validatedData = $data->getData();
94 95
            } elseif (is_string($attribute)) {
95
                /** @psalm-suppress MixedAssignment */
96 95
                $validatedData = $data->getAttributeValue($attribute);
97 95
                $context = $context->withAttribute($attribute);
98
            } else {
99
                $message = sprintf(
100
                    'An attribute can only have an integer or a string type. %s given.',
101
                    get_debug_type($attribute),
102
                );
103
104
                throw new InvalidArgumentException($message);
105
            }
106
107 704
            $tempResult = $this->validateInternal($validatedData, $attributeRules, $context);
108
109 679
            foreach ($tempResult->getErrors() as $error) {
110 395
                $result->addError($error->getMessage(), $error->getParameters(), $error->getValuePath());
111
            }
112
113 679
            $results[] = $result;
114
        }
115
116 690
        foreach ($results as $result) {
117 679
            foreach ($result->getErrors() as $error) {
118 395
                $compoundResult->addError(
119 395
                    $this->translator->translate($error->getMessage(), $error->getParameters()),
120 395
                    $error->getParameters(),
121 395
                    $error->getValuePath()
122
                );
123
            }
124
        }
125
126 690
        if ($data instanceof PostValidationHookInterface) {
127
            $data->processValidationResult($compoundResult);
128
        }
129
130 690
        return $compoundResult;
131
    }
132
133 715
    #[Pure]
134
    private function normalizeDataSet(mixed $data): DataSetInterface
135
    {
136 715
        if ($data instanceof DataSetInterface) {
137 71
            return $data;
138
        }
139
140 649
        if (is_object($data)) {
141 38
            return new ObjectDataSet($data);
142
        }
143
144 615
        if (is_array($data)) {
145 109
            return new ArrayDataSet($data);
146
        }
147
148 532
        return new SingleValueDataSet($data);
149
    }
150
151
    /**
152
     * @param iterable<RuleInterface> $rules
153
     */
154 704
    private function validateInternal(mixed $value, iterable $rules, ValidationContext $context): Result
155
    {
156 704
        $compoundResult = new Result();
157 704
        foreach ($rules as $rule) {
158 704
            if ($this->preValidate($value, $context, $rule)) {
159 27
                continue;
160
            }
161
162 698
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
163 696
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
164 673
            if ($ruleResult->isValid()) {
165 301
                continue;
166
            }
167
168 395
            $context->setParameter($this->parameterPreviousRulesErrored, true);
169
170 395
            foreach ($ruleResult->getErrors() as $error) {
171 395
                $valuePath = $error->getValuePath();
172 395
                if ($context->getAttribute() !== null) {
173 71
                    $valuePath = [$context->getAttribute(), ...$valuePath];
174
                }
175 395
                $compoundResult->addError($error->getMessage(), $error->getParameters(), $valuePath);
176
            }
177
        }
178 679
        return $compoundResult;
179
    }
180
181
    /**
182
     * @return iterable<RuleInterface>
183
     */
184 704
    private function normalizeRules(iterable $rules): iterable
185
    {
186
        /** @var mixed $rule */
187 704
        foreach ($rules as $rule) {
188 704
            yield $this->normalizeRule($rule);
189
        }
190
    }
191
192 704
    private function normalizeRule(mixed $rule): RuleInterface
193
    {
194 704
        if (is_callable($rule)) {
195 3
            return new Callback($rule);
196
        }
197
198 704
        if (!$rule instanceof RuleInterface) {
199
            throw new InvalidArgumentException(
200
                sprintf(
201
                    'Rule should be either an instance of %s or a callable, %s given.',
202
                    RuleInterface::class,
203
                    get_debug_type($rule)
204
                )
205
            );
206
        }
207
208 704
        if ($rule instanceof SkipOnEmptyInterface && $rule->getSkipOnEmpty() === null) {
209 617
            $rule = $rule->skipOnEmpty($this->defaultSkipOnEmptyCallback);
210
        }
211
212 704
        return $rule;
213
    }
214
}
215