Passed
Pull Request — master (#282)
by Alexander
04:15 queued 01:44
created

Validator   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 151
Duplicated Lines 0 %

Test Coverage

Coverage 93.94%

Importance

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