Test Failed
Pull Request — master (#222)
by Rustam
02:30
created

Validator   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Test Coverage

Coverage 95%

Importance

Changes 8
Bugs 3 Features 0
Metric Value
wmc 23
eloc 58
c 8
b 3
f 0
dl 0
loc 136
rs 10
ccs 19
cts 20
cp 0.95

6 Methods

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