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

Validator   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 160
Duplicated Lines 0 %

Test Coverage

Coverage 92.75%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 29
eloc 70
c 5
b 0
f 0
dl 0
loc 160
ccs 64
cts 69
cp 0.9275
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A addErrors() 0 6 2
A normalizeRule() 0 17 3
B validate() 0 55 10
B validateInternal() 0 28 7
A normalizeRules() 0 4 2
A normalizeDataSet() 0 12 4
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 = [];
40
41 36
        if ($data instanceof DataSetInterface) {
0 ignored issues
show
introduced by
$data is always a sub-type of Yiisoft\Validator\DataSetInterface.
Loading history...
42 36
            $rulesByAttribute = (array) ((new AttributeDataSet($data))->getRules());
43
        }
44
45 36
        if ($rules === null && $data instanceof RulesProviderInterface) {
46 2
            $rules = $data->getRules();
47
        }
48
49 36
        if ($rulesByAttribute !== []) {
50
            $rules = array_merge($rulesByAttribute, $rules ?? []);
0 ignored issues
show
Bug introduced by
It seems like $rules ?? array() can also be of type iterable; however, parameter $arrays of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

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