Passed
Pull Request — master (#320)
by Dmitriy
12:18
created

Validator::validate()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 44
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6.0033

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 25
c 5
b 1
f 0
dl 0
loc 44
ccs 21
cts 22
cp 0.9545
rs 8.8977
cc 6
nc 20
nop 3
crap 6.0033
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 Yiisoft\Validator\DataSet\ArrayDataSet;
13
use Yiisoft\Validator\DataSet\MixedDataSet;
14
use Yiisoft\Validator\DataSet\ObjectDataSet;
15
use Yiisoft\Validator\Rule\Callback;
16
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
17
18
use function is_callable;
19
use function is_int;
20
21
/**
22
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
23
 */
24
final class Validator implements ValidatorInterface
25
{
26
    use PreValidateTrait;
27
28
    /**
29
     * @var callable
30
     */
31
    private $defaultSkipOnEmptyCallback;
32
33 635
    public function __construct(
34
        private RuleHandlerResolverInterface $ruleHandlerResolver,
35
36
        /**
37
         * @var bool|callable|null
38
         */
39
        $defaultSkipOnEmpty = null,
40
    ) {
41 635
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
42
    }
43
44
    /**
45
     * @param DataSetInterface|mixed|RulesProviderInterface $data
46
     * @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...
47
     *
48
     * @throws ContainerExceptionInterface
49
     * @throws NotFoundExceptionInterface
50
     */
51 107
    public function validate(
52
        mixed $data,
53
        iterable|RulesProviderInterface|null $rules = null,
54
        ?ValidationContext $context = null,
55
    ): Result {
56 107
        $data = $this->normalizeDataSet($data);
57
58 107
        $compoundResult = new Result();
59 107
        $context = new ValidationContext($context?->getValidator() ?? $this, $context?->getDataSet() ?? $data, $context?->getAttribute() ?? null, $context?->getParameters() ?? []);
60 107
        $results = [];
61
62 107
        foreach ($rules ?? [] as $attribute => $attributeRules) {
63 97
            $result = new Result();
64
65 97
            $tempRule = is_iterable($attributeRules) ? $attributeRules : [$attributeRules];
66 97
            $attributeRules = $this->normalizeRules($tempRule);
67
68 97
            if (is_int($attribute)) {
69 37
                $validatedData = $data->getData();
70 37
                $validatedContext = $context;
71
            } else {
72 64
                $validatedData = $data->getAttributeValue($attribute);
73 64
                $validatedContext = $context->withAttribute($attribute);
74
            }
75
76 97
            $tempResult = $this->validateInternal(
77
                $validatedData,
78
                $attributeRules,
79
                $validatedContext
80
            );
81
82 95
            $result = $this->addErrors($result, $tempResult->getErrors());
83 95
            $results[] = $result;
84
        }
85
86 105
        foreach ($results as $result) {
87 95
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
88
        }
89
90 105
        if ($data instanceof PostValidationHookInterface) {
91
            $data->processValidationResult($compoundResult);
92
        }
93
94 105
        return $compoundResult;
95
    }
96
97
    /**
98
     * @param iterable<Closure|Closure[]|RuleInterface|RuleInterface[]> $rules
99
     *
100
     * @throws ContainerExceptionInterface
101
     * @throws NotFoundExceptionInterface
102
     */
103 97
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
104
    {
105 97
        $compoundResult = new Result();
106 97
        foreach ($rules as $rule) {
107 97
            if ($rule instanceof BeforeValidationInterface) {
108 94
                $preValidateResult = $this->preValidate($value, $context, $rule);
109 94
                if ($preValidateResult) {
110 15
                    continue;
111
                }
112
            }
113
114 92
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
115 90
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
116 90
            if ($ruleResult->isValid()) {
117 36
                continue;
118
            }
119
120 74
            $context->setParameter($this->parameterPreviousRulesErrored, true);
121
122 74
            foreach ($ruleResult->getErrors() as $error) {
123 74
                $valuePath = $error->getValuePath();
124 74
                if ($context->getAttribute() !== null) {
125 53
                    $valuePath = [$context->getAttribute(), ...$valuePath];
126
                }
127 74
                $compoundResult->addError($error->getMessage(), $valuePath, $error->getParameters());
128
            }
129
        }
130 95
        return $compoundResult;
131
    }
132
133
    /**
134
     * @param array $rules
135
     *
136
     * @return iterable<RuleInterface>
137
     */
138 97
    private function normalizeRules(iterable $rules): iterable
139
    {
140 97
        foreach ($rules as $rule) {
141 97
            yield $this->normalizeRule($rule);
142
        }
143
    }
144
145 97
    private function normalizeRule($rule): RuleInterface
146
    {
147 97
        if (is_callable($rule)) {
148 3
            return new Callback($rule);
149
        }
150
151 97
        if (!$rule instanceof RuleInterface) {
152
            throw new InvalidArgumentException(
153
                sprintf(
154
                    'Rule should be either an instance of %s or a callable, %s given.',
155
                    RuleInterface::class,
156
                    get_debug_type($rule)
157
                )
158
            );
159
        }
160
161 97
        if ($rule instanceof SkipOnEmptyInterface && $rule->getSkipOnEmpty() === null) {
162 92
            $rule = $rule->skipOnEmpty($this->defaultSkipOnEmptyCallback);
163
        }
164
165 97
        return $rule;
166
    }
167
168 107
    #[Pure]
169
    private function normalizeDataSet($data): DataSetInterface
170
    {
171 107
        if ($data instanceof DataSetInterface) {
172 107
            return $data;
173
        }
174
175
        if (is_object($data)) {
176
            return new ObjectDataSet($data);
177
        }
178
179
        if (is_array($data)) {
180
            return new ArrayDataSet($data);
181
        }
182
183
        return new MixedDataSet($data);
184
    }
185
186
    /**
187
     * @param Result $result
188
     * @param Error[] $errors
189
     *
190
     * @return Result
191
     */
192 95
    private function addErrors(Result $result, array $errors): Result
193
    {
194 95
        foreach ($errors as $error) {
195 74
            $result->addError($error->getMessage(), $error->getValuePath(), $error->getParameters());
196
        }
197 95
        return $result;
198
    }
199
}
200