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