Passed
Pull Request — master (#270)
by Rustam
02:15
created

Validator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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