Passed
Pull Request — master (#288)
by Alexander
10:50 queued 07:32
created

Validator   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 171
Duplicated Lines 0 %

Test Coverage

Coverage 86.49%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 33
eloc 75
c 4
b 1
f 0
dl 0
loc 171
ccs 64
cts 74
cp 0.8649
rs 9.76

7 Methods

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

181
            /** @scrutinizer ignore-call */ 
182
            $rule = $rule->skipOnEmpty($this->skipOnEmpty);
Loading history...
182
        }
183
184 35
        if ($this->skipOnEmpty !== null) {
185
            $rule = $rule->skipOnEmptyCallback($this->skipOnEmptyCallback);
186
        }
187
188 35
        return $rule;
189
    }
190
191 33
    private function addErrors(Result $result, array $errors): Result
192
    {
193 33
        foreach ($errors as $error) {
194 18
            $result->addError($error->getMessage(), $error->getValuePath());
195
        }
196 33
        return $result;
197
    }
198
}
199