Passed
Pull Request — master (#245)
by Rustam
12:07
created

Validator::validateInternal()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 28
ccs 18
cts 18
cp 1
rs 8.8333
cc 7
nc 10
nop 3
crap 7
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\PreValidateTrait;
16
use function is_array;
17
use function is_object;
18
19
/**
20
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
21
 */
22
final class Validator implements ValidatorInterface
23
{
24
    use PreValidateTrait;
25
26 534
    public function __construct(private RuleHandlerResolverInterface $ruleHandlerResolver)
27
    {
28
    }
29
30
    /**
31
     * @param DataSetInterface|mixed|RulesProviderInterface $data
32
     * @param iterable<RuleInterface|RuleInterface[]> $rules
33
     */
34 38
    public function validate($data, iterable $rules = []): Result
35
    {
36 38
        $data = $this->normalizeDataSet($data);
37 38
        if ($data instanceof RulesProviderInterface) {
38 2
            $rules = $data->getRules();
39
        }
40
41 38
        $context = new ValidationContext($this, $data);
42 38
        $compoundResult = new Result();
43
44 38
        $results = [];
45
46 38
        foreach ($rules as $attribute => $attributeRules) {
47 38
            $result = new Result();
48
49 38
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
50 38
            $attributeRules = $this->normalizeRules($tempRule);
51
52 38
            if (is_int($attribute)) {
53 24
                $validatedData = $data->getData();
54 24
                $validatedContext = $context;
55
            } else {
56 14
                $validatedData = $data->getAttributeValue($attribute);
57 14
                $validatedContext = $context->withAttribute($attribute);
58
            }
59
60 38
            $tempResult = $this->validateInternal(
61
                $validatedData,
62
                $attributeRules,
63
                $validatedContext
64
            );
65
66 37
            $result = $this->addErrors($result, $tempResult->getErrors());
67 37
            $results[] = $result;
68
        }
69
70 37
        foreach ($results as $result) {
71 37
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
72
        }
73
74 37
        if ($data instanceof PostValidationHookInterface) {
75
            $data->processValidationResult($compoundResult);
76
        }
77
78 37
        return $compoundResult;
79
    }
80
81 38
    #[Pure]
82
    private function normalizeDataSet($data): DataSetInterface
83
    {
84 38
        if ($data instanceof DataSetInterface) {
85 7
            return $data;
86
        }
87
88 31
        if (is_object($data) || is_array($data)) {
89 6
            return new ArrayDataSet((array)$data);
90
        }
91
92 30
        return new ScalarDataSet($data);
93
    }
94
95
    /**
96
     * @param $value
97
     * @param iterable<RuleInterface> $rules
98
     * @param ValidationContext $context
99
     *
100
     * @throws ContainerExceptionInterface
101
     * @throws NotFoundExceptionInterface
102
     *
103
     * @return Result
104
     */
105 38
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
106
    {
107 38
        $compoundResult = new Result();
108 38
        foreach ($rules as $rule) {
109 38
            if ($rule instanceof BeforeValidationInterface) {
110 37
                $preValidateResult = $this->preValidate($value, $context, $rule);
111 37
                if ($preValidateResult) {
112 2
                    continue;
113
                }
114
            }
115
116 36
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
117 35
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
118 35
            if ($ruleResult->isValid()) {
119 24
                continue;
120
            }
121
122 22
            $context->setParameter($this->parameterPreviousRulesErrored, true);
123
124 22
            foreach ($ruleResult->getErrors() as $error) {
125 22
                $valuePath = $error->getValuePath();
126 22
                if ($context->getAttribute() !== null) {
127 3
                    $valuePath = [$context->getAttribute()] + $valuePath;
128
                }
129 22
                $compoundResult->addError($error->getMessage(), $valuePath);
130
            }
131
        }
132 37
        return $compoundResult;
133
    }
134
135
    /**
136
     * @param array $rules
137
     *
138
     * @return iterable<RuleInterface>
139
     */
140 38
    private function normalizeRules(iterable $rules): iterable
141
    {
142 38
        foreach ($rules as $rule) {
143 38
            yield $this->normalizeRule($rule);
144
        }
145
    }
146
147 38
    private function normalizeRule($rule): RuleInterface
148
    {
149 38
        if (is_callable($rule)) {
150 3
            return new Callback($rule);
151
        }
152
153 38
        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 38
        return $rule;
164
    }
165
166 37
    private function addErrors(Result $result, array $errors): Result
167
    {
168 37
        foreach ($errors as $error) {
169 22
            $result->addError($error->getMessage(), $error->getValuePath());
170
        }
171 37
        return $result;
172
    }
173
}
174