Passed
Pull Request — master (#270)
by Rustam
02:25
created

Validator   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 153
Duplicated Lines 0 %

Test Coverage

Coverage 92.54%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 29
eloc 68
c 4
b 0
f 0
dl 0
loc 153
ccs 62
cts 67
cp 0.9254
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A addErrors() 0 6 2
A normalizeRule() 0 17 3
B validate() 0 46 8
B validateInternal() 0 28 7
A normalizeRules() 0 4 2
A normalizeDataSet() 0 14 6
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\AttributeDataSet;
13
use Yiisoft\Validator\DataSet\ScalarDataSet;
14
use Yiisoft\Validator\Rule\Callback;
15
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
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 PreValidateTrait;
26
27 571
    public function __construct(private RuleHandlerResolverInterface $ruleHandlerResolver)
28
    {
29
    }
30
31
    /**
32
     * @param DataSetInterface|mixed|RulesProviderInterface $data
33
     * @param iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]> $rules
34
     */
35 35
    public function validate($data, iterable $rules = []): Result
36
    {
37 35
        $hasRules = $rules !== [];
38 35
        $data = $this->normalizeDataSet($data, $hasRules);
39 35
        if (!$hasRules && $data instanceof RulesProviderInterface) {
40 2
            $rules = $data->getRules();
41
        }
42
43 35
        $context = new ValidationContext($this, $data);
44 35
        $compoundResult = new Result();
45
46 35
        $results = [];
47
48 35
        foreach ($rules as $attribute => $attributeRules) {
49 35
            $result = new Result();
50
51 35
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
52 35
            $attributeRules = $this->normalizeRules($tempRule);
53
54 35
            if (is_int($attribute)) {
55 19
                $validatedData = $data->getData();
56 19
                $validatedContext = $context;
57
            } else {
58 16
                $validatedData = $data->getAttributeValue($attribute);
59 16
                $validatedContext = $context->withAttribute($attribute);
60
            }
61
62 35
            $tempResult = $this->validateInternal(
63
                $validatedData,
64
                $attributeRules,
65
                $validatedContext
66
            );
67
68 33
            $result = $this->addErrors($result, $tempResult->getErrors());
69 33
            $results[] = $result;
70
        }
71
72 33
        foreach ($results as $result) {
73 33
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
74
        }
75
76 33
        if ($data instanceof PostValidationHookInterface) {
77
            $data->processValidationResult($compoundResult);
78
        }
79
80 33
        return $compoundResult;
81
    }
82
83 35
    #[Pure]
84
    private function normalizeDataSet($data, bool $hasRules): DataSetInterface
85
    {
86 35
        if ($data instanceof DataSetInterface) {
87 9
            return (!$hasRules && !$data instanceof RulesProviderInterface)
88
                ? new AttributeDataSet($data)
89 9
                : $data;
90
        }
91
92 26
        if (is_object($data) || is_array($data)) {
93 6
            return new ArrayDataSet((array)$data);
94
        }
95
96 25
        return new ScalarDataSet($data);
97
    }
98
99
    /**
100
     * @param $value
101
     * @param iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]> $rules
102
     * @param ValidationContext $context
103
     *
104
     * @throws ContainerExceptionInterface
105
     * @throws NotFoundExceptionInterface
106
     *
107
     * @return Result
108
     */
109 35
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
110
    {
111 35
        $compoundResult = new Result();
112 35
        foreach ($rules as $rule) {
113 35
            if ($rule instanceof BeforeValidationInterface) {
114 33
                $preValidateResult = $this->preValidate($value, $context, $rule);
115 33
                if ($preValidateResult) {
116 2
                    continue;
117
                }
118
            }
119
120 33
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
121 31
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
122 31
            if ($ruleResult->isValid()) {
123 21
                continue;
124
            }
125
126 18
            $context->setParameter($this->parameterPreviousRulesErrored, true);
127
128 18
            foreach ($ruleResult->getErrors() as $error) {
129 18
                $valuePath = $error->getValuePath();
130 18
                if ($context->getAttribute() !== null) {
131 3
                    $valuePath = [$context->getAttribute()] + $valuePath;
132
                }
133 18
                $compoundResult->addError($error->getMessage(), $valuePath);
134
            }
135
        }
136 33
        return $compoundResult;
137
    }
138
139
    /**
140
     * @param array $rules
141
     *
142
     * @return iterable<RuleInterface>
143
     */
144 35
    private function normalizeRules(iterable $rules): iterable
145
    {
146 35
        foreach ($rules as $rule) {
147 35
            yield $this->normalizeRule($rule);
148
        }
149
    }
150
151 35
    private function normalizeRule($rule): RuleInterface
152
    {
153 35
        if (is_callable($rule)) {
154 3
            return new Callback($rule);
155
        }
156
157 35
        if (!$rule instanceof RuleInterface) {
158
            throw new InvalidArgumentException(
159
                sprintf(
160
                    'Rule should be either an instance of %s or a callable, %s given.',
161
                    RuleInterface::class,
162
                    gettype($rule)
163
                )
164
            );
165
        }
166
167 35
        return $rule;
168
    }
169
170 33
    private function addErrors(Result $result, array $errors): Result
171
    {
172 33
        foreach ($errors as $error) {
173 18
            $result->addError($error->getMessage(), $error->getValuePath());
174
        }
175 33
        return $result;
176
    }
177
}
178