Passed
Pull Request — master (#291)
by Sergei
02:18
created

Validator::normalizeDataSet()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

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