Passed
Pull Request — master (#222)
by Alexander
04:26 queued 02:14
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
            $preValidateResult = $this->preValidate($value, $context, $rule);
116 28
            if ($preValidateResult !== null && $preValidateResult->isValid()) {
117 1
                continue;
118
            }
119
120 27
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
121 27
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
122 27
            if ($ruleResult->isValid()) {
123 22
                continue;
124
            }
125
126 14
            $context->setParameter(self::PARAMETER_PREVIOUS_RULES_ERRORED, true);
127
128 14
            foreach ($ruleResult->getErrors() as $error) {
129 14
                $compoundResult->addError($error->getMessage(), $error->getValuePath());
130
            }
131
        }
132 28
        return $compoundResult;
133
    }
134
135
    /**
136
     * @param array $rules
137
     *
138
     * @return iterable<RuleInterface>
139
     */
140 28
    private function normalizeRules(iterable $rules): iterable
141
    {
142 28
        foreach ($rules as $rule) {
143 28
            yield $this->normalizeRule($rule);
144
        }
145
    }
146
147 28
    private function normalizeRule($rule): RuleInterface
148
    {
149 28
        if (is_callable($rule)) {
150 3
            return new Callback($rule);
151
        }
152
153 28
        if (!$rule instanceof RuleInterface) {
154
            throw new InvalidArgumentException(
155
                sprintf(
156
                    'Rule should be either an instance of %s or a callable, %s given.',
157
                    RuleInterface::class,
158
                    gettype($rule)
159
                )
160
            );
161
        }
162
163 28
        return $rule;
164
    }
165
166 28
    private function addErrors(Result $result, array $errors): Result
167
    {
168 28
        foreach ($errors as $error) {
169 14
            $result->addError($error->getMessage(), $error->getValuePath());
170
        }
171 28
        return $result;
172
    }
173
174 28
    private function preValidate(
175
        $value,
176
        ValidationContext $context,
177
        PreValidatableRuleInterface $rule
178
    ): ?Result {
179 28
        if ($rule->isSkipOnEmpty() && $this->isEmpty($value)) {
180 1
            return new Result();
181
        }
182
183 27
        if ($rule->isSkipOnError() && $context->getParameter(self::PARAMETER_PREVIOUS_RULES_ERRORED) === true) {
184
            return new Result();
185
        }
186
187 27
        if (is_callable($rule->getWhen()) && !($rule->getWhen())($value, $context)) {
188
            return new Result();
189
        }
190
191 27
        return null;
192
    }
193
}
194