Passed
Pull Request — master (#222)
by Alexander
02:58
created

Validator::validate()   B

Complexity

Conditions 7
Paths 40

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 7.0035

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 27
c 4
b 0
f 0
dl 0
loc 45
ccs 23
cts 24
cp 0.9583
rs 8.5546
cc 7
nc 40
nop 2
crap 7.0035
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;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Validator\Rule\Callback was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use function is_array;
15
use function is_object;
16
17
/**
18
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
19
 */
20
final class Validator implements ValidatorInterface
21
{
22
    public const PARAMETER_PREVIOUS_RULES_ERRORED = 'previousRulesErrored';
23
24
    private RuleHandlerResolverInterface $ruleHandlerResolver;
25
26 518
    public function __construct(RuleHandlerResolverInterface $ruleHandlerResolver)
27
    {
28 518
        $this->ruleHandlerResolver = $ruleHandlerResolver;
29
    }
30
31
    /**
32
     * @param DataSetInterface|mixed|RulesProviderInterface $data
33
     * @param iterable<RuleInterface|RuleInterface[]> $rules
34
     */
35 28
    public function validate($data, iterable $rules = []): Result
36
    {
37 28
        $data = $this->normalizeDataSet($data);
38 28
        if ($data instanceof RulesProviderInterface) {
39 2
            $rules = $data->getRules();
40
        }
41
42 28
        $context = new ValidationContext($this, $data);
43 28
        $compoundResult = new Result();
44
45 28
        $results = [];
46
47 28
        foreach ($rules as $attribute => $attributeRules) {
48 28
            $result = new Result();
49
50 28
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
51 28
            $attributeRules = $this->normalizeRules($tempRule);
52
53 28
            if (is_int($attribute)) {
54 16
                $validatedData = $data->getData();
55 16
                $validatedContext = $context;
56
            } else {
57 12
                $validatedData = $data->getAttributeValue($attribute);
58 12
                $validatedContext = $context->withAttribute($attribute);
59
            }
60
61 28
            $tempResult = $this->validateInternal(
62
                $validatedData,
63
                $attributeRules,
64
                $validatedContext
65
            );
66
67 28
            $result = $this->addErrors($result, $tempResult->getErrors());
68 28
            $results[] = $result;
69
        }
70
71 28
        foreach ($results as $result) {
72 28
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
73
        }
74
75 28
        if ($data instanceof PostValidationHookInterface) {
76
            $data->processValidationResult($compoundResult);
77
        }
78
79 28
        return $compoundResult;
80
    }
81
82 28
    #[Pure]
83
    private function normalizeDataSet($data): DataSetInterface
84
    {
85 28
        if ($data instanceof DataSetInterface) {
86 5
            return $data;
87
        }
88
89 23
        if (is_object($data) || is_array($data)) {
90 4
            return new ArrayDataSet((array)$data);
91
        }
92
93 22
        return new ScalarDataSet($data);
94
    }
95
96
    /**
97
     * @param $value
98
     * @param iterable<RuleInterface> $rules
99
     * @param ValidationContext $context
100
     *
101
     * @throws ContainerExceptionInterface
102
     * @throws NotFoundExceptionInterface
103
     *
104
     * @return Result
105
     */
106 28
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
107
    {
108 28
        $compoundResult = new Result();
109 28
        foreach ($rules as $rule) {
110 28
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
111 28
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
112 28
            if ($ruleResult->isValid()) {
113 23
                continue;
114
            }
115
116 14
            $context->setParameter(self::PARAMETER_PREVIOUS_RULES_ERRORED, true);
117
118 14
            foreach ($ruleResult->getErrors() as $error) {
119 14
                $compoundResult->addError($error->getMessage(), $error->getValuePath());
120
            }
121
        }
122 28
        return $compoundResult;
123
    }
124
125
    /**
126
     * @param array $rules
127
     *
128
     * @return iterable<RuleInterface>
129
     */
130 28
    private function normalizeRules(iterable $rules): iterable
131
    {
132 28
        foreach ($rules as $rule) {
133 28
            yield $this->normalizeRule($rule);
134
        }
135
    }
136
137 28
    private function normalizeRule($rule): RuleInterface
138
    {
139 28
        if (is_callable($rule)) {
140 3
            return new Callback($rule);
141
        }
142
143 28
        if (!$rule instanceof RuleInterface) {
144
            throw new InvalidArgumentException(sprintf(
145
                'Rule should be either an instance of %s or a callable, %s given.',
146
                RuleInterface::class,
147
                gettype($rule)
148
            ));
149
        }
150
151 28
        return $rule;
152
    }
153
154 28
    private function addErrors(Result $result, array $errors): Result
155
    {
156 28
        foreach ($errors as $error) {
157 14
            $result->addError($error->getMessage(), $error->getValuePath());
158
        }
159 28
        return $result;
160
    }
161
}
162