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