Passed
Pull Request — master (#222)
by Rustam
02:28
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 520
    public function __construct(private RuleHandlerResolverInterface $ruleHandlerResolver)
30
    {
31
    }
32
33
    /**
34
     * @param DataSetInterface|mixed|RulesProviderInterface $data
35
     * @param iterable<RuleInterface|RuleInterface[]> $rules
36
     */
37 30
    public function validate($data, iterable $rules = []): Result
38
    {
39 30
        $data = $this->normalizeDataSet($data);
40 30
        if ($data instanceof RulesProviderInterface) {
41 2
            $rules = $data->getRules();
42
        }
43
44 30
        $context = new ValidationContext($this, $data);
45 30
        $compoundResult = new Result();
46
47 30
        $results = [];
48
49 30
        foreach ($rules as $attribute => $attributeRules) {
50 30
            $result = new Result();
51
52 30
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
53 30
            $attributeRules = $this->normalizeRules($tempRule);
54
55 30
            if (is_int($attribute)) {
56 16
                $validatedData = $data->getData();
57 16
                $validatedContext = $context;
58
            } else {
59 14
                $validatedData = $data->getAttributeValue($attribute);
60 14
                $validatedContext = $context->withAttribute($attribute);
61
            }
62
63 30
            $tempResult = $this->validateInternal(
64
                $validatedData,
65
                $attributeRules,
66
                $validatedContext
67
            );
68
69 29
            $result = $this->addErrors($result, $tempResult->getErrors());
70 29
            $results[] = $result;
71
        }
72
73 29
        foreach ($results as $result) {
74 29
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
75
        }
76
77 29
        if ($data instanceof PostValidationHookInterface) {
78
            $data->processValidationResult($compoundResult);
79
        }
80
81 29
        return $compoundResult;
82
    }
83
84 30
    #[Pure]
85
    private function normalizeDataSet($data): DataSetInterface
86
    {
87 30
        if ($data instanceof DataSetInterface) {
88 7
            return $data;
89
        }
90
91 23
        if (is_object($data) || is_array($data)) {
92 4
            return new ArrayDataSet((array)$data);
93
        }
94
95 22
        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 30
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
109
    {
110 30
        $compoundResult = new Result();
111 30
        foreach ($rules as $rule) {
112 30
            if ($rule instanceof PreValidatableRuleInterface) {
113 29
                $preValidateResult = $this->preValidate($value, $context, $rule);
114 29
                if ($preValidateResult) {
115 2
                    continue;
116
                }
117
            }
118
119 28
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
120 27
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
121 27
            if ($ruleResult->isValid()) {
122 22
                continue;
123
            }
124
125 14
            $context->setParameter(self::PARAMETER_PREVIOUS_RULES_ERRORED, true);
126
127 14
            foreach ($ruleResult->getErrors() as $error) {
128 14
                $compoundResult->addError($error->getMessage(), $error->getValuePath());
129
            }
130
        }
131 29
        return $compoundResult;
132
    }
133
134
    /**
135
     * @param array $rules
136
     *
137
     * @return iterable<RuleInterface>
138
     */
139 30
    private function normalizeRules(iterable $rules): iterable
140
    {
141 30
        foreach ($rules as $rule) {
142 30
            yield $this->normalizeRule($rule);
143
        }
144
    }
145
146 30
    private function normalizeRule($rule): RuleInterface
147
    {
148 30
        if (is_callable($rule)) {
149 3
            return new Callback($rule);
150
        }
151
152 30
        if (!$rule instanceof RuleInterface) {
153
            throw new InvalidArgumentException(
154
                sprintf(
155
                    'Rule should be either an instance of %s or a callable, %s given.',
156
                    RuleInterface::class,
157
                    gettype($rule)
158
                )
159
            );
160
        }
161
162 30
        return $rule;
163
    }
164
165 29
    private function addErrors(Result $result, array $errors): Result
166
    {
167 29
        foreach ($errors as $error) {
168 14
            $result->addError($error->getMessage(), $error->getValuePath());
169
        }
170 29
        return $result;
171
    }
172
173 29
    private function preValidate(
174
        $value,
175
        ValidationContext $context,
176
        PreValidatableRuleInterface $rule
177
    ): bool {
178 29
        if ($rule->isSkipOnEmpty() && $this->isEmpty($value)) {
179 1
            return true;
180
        }
181
182 28
        if ($rule->isSkipOnError() && $context->getParameter(self::PARAMETER_PREVIOUS_RULES_ERRORED) === true) {
183
            return true;
184
        }
185
186 28
        return is_callable($rule->getWhen()) && !($rule->getWhen())($value, $context);
187
    }
188
}
189