Passed
Pull Request — master (#222)
by Rustam
02:32
created

Validator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 95%

Importance

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