Passed
Pull Request — master (#282)
by Wilmer
02:29
created

Validator::validate()   B

Complexity

Conditions 8
Paths 40

Size

Total Lines 49
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 8.0032

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 30
c 7
b 1
f 0
dl 0
loc 49
ccs 26
cts 27
cp 0.963
rs 8.1954
cc 8
nc 40
nop 2
crap 8.0032
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use InvalidArgumentException;
8
use JetBrains\PhpStorm\Pure;
9
use Psr\Container\ContainerExceptionInterface;
10
use Psr\Container\NotFoundExceptionInterface;
11
use Yiisoft\Validator\DataSet\AttributeDataSet;
12
use Yiisoft\Validator\DataSet\ArrayDataSet;
13
use Yiisoft\Validator\DataSet\ScalarDataSet;
14
use Yiisoft\Validator\Rule\Callback;
15
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
16
17
use function is_array;
18
use function is_object;
19
20
/**
21
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
22
 */
23
final class Validator implements ValidatorInterface
24
{
25
    use PreValidateTrait;
26
27 572
    public function __construct(private RuleHandlerResolverInterface $ruleHandlerResolver)
28
    {
29
    }
30
31
    /**
32
     * @param DataSetInterface|mixed|RulesProviderInterface $data
33
     * @param iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>|null $rules
34
     */
35 36
    public function validate(mixed $data, ?iterable $rules = null): Result
36
    {
37 36
        $data = $this->normalizeDataSet($data);
38
39 36
        $rulesByAttribute = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $rulesByAttribute is dead and can be removed.
Loading history...
40
41 36
        if ($rules === null && $data instanceof RulesProviderInterface) {
42 2
            $rules = (array) $data->getRules();
43 2
            $rulesByAttribute = (array) ((new AttributeDataSet($data))->getRules());
44 2
            $rules = array_merge($rulesByAttribute, $rules);
45
        }
46
47 36
        $compoundResult = new Result();
48 36
        $context = new ValidationContext($this, $data);
49 36
        $results = [];
50
51 36
        foreach ($rules ?? [] as $attribute => $attributeRules) {
52 35
            $result = new Result();
53
54 35
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
55 35
            $attributeRules = $this->normalizeRules($tempRule);
56
57 35
            if (is_int($attribute)) {
58 19
                $validatedData = $data->getData();
59 19
                $validatedContext = $context;
60
            } else {
61 16
                $validatedData = $data->getAttributeValue($attribute);
62 16
                $validatedContext = $context->withAttribute($attribute);
63
            }
64
65 35
            $tempResult = $this->validateInternal(
66
                $validatedData,
67
                $attributeRules,
68
                $validatedContext
69
            );
70
71 33
            $result = $this->addErrors($result, $tempResult->getErrors());
72 33
            $results[] = $result;
73
        }
74
75 34
        foreach ($results as $result) {
76 33
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
77
        }
78
79 34
        if ($data instanceof PostValidationHookInterface) {
80
            $data->processValidationResult($compoundResult);
81
        }
82
83 34
        return $compoundResult;
84
    }
85
86 36
    #[Pure]
87
    private function normalizeDataSet($data): DataSetInterface
88
    {
89 36
        if ($data instanceof DataSetInterface) {
90 10
            return $data;
91
        }
92
93 26
        if (is_object($data) || is_array($data)) {
94 6
            return new ArrayDataSet((array)$data);
95
        }
96
97 25
        return new ScalarDataSet($data);
98
    }
99
100
    /**
101
     * @param $value
102
     * @param iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]> $rules
103
     * @param ValidationContext $context
104
     *
105
     * @throws ContainerExceptionInterface
106
     * @throws NotFoundExceptionInterface
107
     *
108
     * @return Result
109
     */
110 35
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
111
    {
112 35
        $compoundResult = new Result();
113 35
        foreach ($rules as $rule) {
114 35
            if ($rule instanceof BeforeValidationInterface) {
115 33
                $preValidateResult = $this->preValidate($value, $context, $rule);
116 33
                if ($preValidateResult) {
117 2
                    continue;
118
                }
119
            }
120
121 33
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
122 31
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
123 31
            if ($ruleResult->isValid()) {
124 21
                continue;
125
            }
126
127 18
            $context->setParameter($this->parameterPreviousRulesErrored, true);
128
129 18
            foreach ($ruleResult->getErrors() as $error) {
130 18
                $valuePath = $error->getValuePath();
131 18
                if ($context->getAttribute() !== null) {
132 3
                    $valuePath = [$context->getAttribute()] + $valuePath;
133
                }
134 18
                $compoundResult->addError($error->getMessage(), $valuePath);
135
            }
136
        }
137 33
        return $compoundResult;
138
    }
139
140
    /**
141
     * @param array $rules
142
     *
143
     * @return iterable<RuleInterface>
144
     */
145 35
    private function normalizeRules(iterable $rules): iterable
146
    {
147 35
        foreach ($rules as $rule) {
148 35
            yield $this->normalizeRule($rule);
149
        }
150
    }
151
152 35
    private function normalizeRule($rule): RuleInterface
153
    {
154 35
        if (is_callable($rule)) {
155 3
            return new Callback($rule);
156
        }
157
158 35
        if (!$rule instanceof RuleInterface) {
159
            throw new InvalidArgumentException(
160
                sprintf(
161
                    'Rule should be either an instance of %s or a callable, %s given.',
162
                    RuleInterface::class,
163
                    gettype($rule)
164
                )
165
            );
166
        }
167
168 35
        return $rule;
169
    }
170
171 33
    private function addErrors(Result $result, array $errors): Result
172
    {
173 33
        foreach ($errors as $error) {
174 18
            $result->addError($error->getMessage(), $error->getValuePath());
175
        }
176 33
        return $result;
177
    }
178
}
179