Passed
Pull Request — master (#222)
by Alexander
04:32 queued 02:10
created

Validator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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
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
            foreach ($tempResult->getErrors() as $error) {
68 14
                $result->addError($error->getMessage(), $error->getValuePath());
69
            }
70 28
            $results[] = $result;
71
        }
72
73 28
        foreach ($results as $result) {
74 28
            foreach ($result->getErrors() as $error) {
75 14
                $compoundResult->addError($error->getMessage(), $error->getValuePath());
76
            }
77
        }
78
79 28
        if ($data instanceof PostValidationHookInterface) {
80
            $data->processValidationResult($compoundResult);
81
        }
82
83 28
        return $compoundResult;
84
    }
85
86 28
    #[Pure]
87
    private function normalizeDataSet($data): DataSetInterface
88
    {
89 28
        if ($data instanceof DataSetInterface) {
90 5
            return $data;
91
        }
92
93 23
        if (is_object($data) || is_array($data)) {
94 4
            return new ArrayDataSet((array)$data);
95
        }
96
97 22
        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 28
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
111
    {
112 28
        $compoundResult = new Result();
113 28
        foreach ($rules as $rule) {
114 28
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
115 28
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
116 28
            if ($ruleResult->isValid()) {
117 23
                continue;
118
            }
119
120 14
            $context->setParameter(self::PARAMETER_PREVIOUS_RULES_ERRORED, true);
121
122 14
            foreach ($ruleResult->getErrors() as $error) {
123 14
                $compoundResult->addError($error->getMessage(), $error->getValuePath());
124
            }
125
        }
126 28
        return $compoundResult;
127
    }
128
129
    /**
130
     * @param array $rules
131
     *
132
     * @return iterable<RuleInterface>
133
     */
134 28
    private function normalizeRules(iterable $rules): iterable
135
    {
136 28
        foreach ($rules as $rule) {
137 28
            yield $this->normalizeRule($rule);
138
        }
139
    }
140
141 28
    private function normalizeRule($rule): RuleInterface
142
    {
143 28
        if (is_callable($rule)) {
144 3
            return new Callback($rule);
145
        }
146
147 28
        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 28
        return $rule;
156
    }
157
}
158