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

Validator::addErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
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
        if ($rules === null && $data instanceof RulesProviderInterface) {
40 2
            $rules = (array) $data->getRules();
41 2
            $rulesByAttribute = (array) ((new AttributeDataSet($data))->getRules());
42 2
            $rules = array_merge($rulesByAttribute, $rules);
43
        }
44
45 36
        $compoundResult = new Result();
46 36
        $context = new ValidationContext($this, $data);
47 36
        $results = [];
48
49 36
        foreach ($rules ?? [] as $attribute => $attributeRules) {
50 35
            $result = new Result();
51
52 35
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
53 35
            $attributeRules = $this->normalizeRules($tempRule);
54
55 35
            if (is_int($attribute)) {
56 19
                $validatedData = $data->getData();
57 19
                $validatedContext = $context;
58
            } else {
59 16
                $validatedData = $data->getAttributeValue($attribute);
60 16
                $validatedContext = $context->withAttribute($attribute);
61
            }
62
63 35
            $tempResult = $this->validateInternal(
64
                $validatedData,
65
                $attributeRules,
66
                $validatedContext
67
            );
68
69 33
            $result = $this->addErrors($result, $tempResult->getErrors());
70 33
            $results[] = $result;
71
        }
72
73 34
        foreach ($results as $result) {
74 33
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
75
        }
76
77 34
        if ($data instanceof PostValidationHookInterface) {
78
            $data->processValidationResult($compoundResult);
79
        }
80
81 34
        return $compoundResult;
82
    }
83
84 36
    #[Pure]
85
    private function normalizeDataSet($data): DataSetInterface
86
    {
87 36
        if ($data instanceof DataSetInterface) {
88 10
            return $data;
89
        }
90
91 26
        if (is_object($data) || is_array($data)) {
92 6
            return new ArrayDataSet((array)$data);
93
        }
94
95 25
        return new ScalarDataSet($data);
96
    }
97
98
    /**
99
     * @param $value
100
     * @param iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]> $rules
101
     * @param ValidationContext $context
102
     *
103
     * @throws ContainerExceptionInterface
104
     * @throws NotFoundExceptionInterface
105
     *
106
     * @return Result
107
     */
108 35
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
109
    {
110 35
        $compoundResult = new Result();
111 35
        foreach ($rules as $rule) {
112 35
            if ($rule instanceof BeforeValidationInterface) {
113 33
                $preValidateResult = $this->preValidate($value, $context, $rule);
114 33
                if ($preValidateResult) {
115 2
                    continue;
116
                }
117
            }
118
119 33
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
120 31
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
121 31
            if ($ruleResult->isValid()) {
122 21
                continue;
123
            }
124
125 18
            $context->setParameter($this->parameterPreviousRulesErrored, true);
126
127 18
            foreach ($ruleResult->getErrors() as $error) {
128 18
                $valuePath = $error->getValuePath();
129 18
                if ($context->getAttribute() !== null) {
130 3
                    $valuePath = [$context->getAttribute()] + $valuePath;
131
                }
132 18
                $compoundResult->addError($error->getMessage(), $valuePath);
133
            }
134
        }
135 33
        return $compoundResult;
136
    }
137
138
    /**
139
     * @param array $rules
140
     *
141
     * @return iterable<RuleInterface>
142
     */
143 35
    private function normalizeRules(iterable $rules): iterable
144
    {
145 35
        foreach ($rules as $rule) {
146 35
            yield $this->normalizeRule($rule);
147
        }
148
    }
149
150 35
    private function normalizeRule($rule): RuleInterface
151
    {
152 35
        if (is_callable($rule)) {
153 3
            return new Callback($rule);
154
        }
155
156 35
        if (!$rule instanceof RuleInterface) {
157
            throw new InvalidArgumentException(
158
                sprintf(
159
                    'Rule should be either an instance of %s or a callable, %s given.',
160
                    RuleInterface::class,
161
                    gettype($rule)
162
                )
163
            );
164
        }
165
166 35
        return $rule;
167
    }
168
169 33
    private function addErrors(Result $result, array $errors): Result
170
    {
171 33
        foreach ($errors as $error) {
172 18
            $result->addError($error->getMessage(), $error->getValuePath());
173
        }
174 33
        return $result;
175
    }
176
}
177