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

Validator   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Test Coverage

Coverage 92.75%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 29
eloc 70
c 4
b 0
f 0
dl 0
loc 159
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 54 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 36
        $rulesByAttribute = [];
39
40 36
        if ($data !== null) {
41 36
            $rulesByAttribute = (new AttributeDataSet($data))->getRules();
42
        }
43
44 36
        if ($rules === null && $data instanceof RulesProviderInterface) {
45 2
            $rules = $data->getRules();
46
        }
47
48 36
        if ($rulesByAttribute !== []) {
49
            $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

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