Passed
Pull Request — master (#303)
by
unknown
12:39 queued 10:19
created

Validator::validate()   C

Complexity

Conditions 12
Paths 80

Size

Total Lines 50
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 12.0524

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 31
c 2
b 0
f 0
dl 0
loc 50
ccs 26
cts 28
cp 0.9286
rs 6.9666
cc 12
nc 80
nop 2
crap 12.0524

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Closure;
8
use InvalidArgumentException;
9
use JetBrains\PhpStorm\Pure;
10
use Psr\Container\ContainerExceptionInterface;
11
use Psr\Container\NotFoundExceptionInterface;
12
use ReflectionProperty;
13
use Traversable;
14
use Yiisoft\Validator\DataSet\ArrayDataSet;
15
use Yiisoft\Validator\DataSet\ObjectDataSet;
16
use Yiisoft\Validator\DataSet\MixedDataSet;
17
use Yiisoft\Validator\Rule\Callback;
18
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
19
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
20
21
use function gettype;
22
use function is_array;
23
use function is_callable;
24
use function is_int;
25
use function is_object;
26
27
/**
28
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
29
 */
30
final class Validator implements ValidatorInterface
31
{
32
    use PreValidateTrait;
33
34
    /**
35
     * @var callable
36
     */
37
    private $defaultSkipOnEmptyCallback;
38
39 636
    public function __construct(
40
        private RuleHandlerResolverInterface $ruleHandlerResolver,
41
        /**
42
         * @var int What visibility levels to use when reading rules from the class specified in `$rules` argument in
43
         * {@see validate()} method.
44
         */
45
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
46
        | ReflectionProperty::IS_PROTECTED
47
        | ReflectionProperty::IS_PUBLIC,
48
49
        /**
50
         * @var bool|callable|null
51
         */
52
        $defaultSkipOnEmpty = null,
53
    ) {
54 636
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
55
    }
56
57
    /**
58
     * @param DataSetInterface|mixed|RulesProviderInterface $data
59
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null $rules
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string|iterable<Cl...sProviderInterface|null at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null.
Loading history...
60
     *
61
     * @throws ContainerExceptionInterface
62
     * @throws NotFoundExceptionInterface
63
     */
64 109
    public function validate(
65
        mixed $data,
66
        iterable|object|string|null $rules = null
67
    ): Result {
68 109
        $data = $this->normalizeDataSet($data);
69 109
        if ($rules === null && $data instanceof RulesProviderInterface) {
70 25
            $rules = $data->getRules();
71 88
        } elseif ($rules instanceof RulesProviderInterface) {
72 2
            $rules = $rules->getRules();
73 86
        } elseif (!$rules instanceof Traversable && !is_array($rules) && $rules !== null) {
74
            $rules = (new AttributesRulesProvider($rules, $this->rulesPropertyVisibility))->getRules();
0 ignored issues
show
Bug introduced by
It seems like $rules can also be of type iterable; however, parameter $source of Yiisoft\Validator\RulesP...Provider::__construct() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

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

74
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $rules, $this->rulesPropertyVisibility))->getRules();
Loading history...
75
        }
76
77 109
        $compoundResult = new Result();
78 109
        $context = new ValidationContext($this, $data);
79 109
        $results = [];
80
81 109
        foreach ($rules ?? [] as $attribute => $attributeRules) {
82 99
            $result = new Result();
83
84 99
            $tempRule = is_array($attributeRules) ? $attributeRules : [$attributeRules];
85 99
            $attributeRules = $this->normalizeRules($tempRule);
86
87 99
            if (is_int($attribute)) {
88 37
                $validatedData = $data->getData();
89 37
                $validatedContext = $context;
90
            } else {
91 66
                $validatedData = $data->getAttributeValue($attribute);
92 66
                $validatedContext = $context->withAttribute($attribute);
93
            }
94
95 99
            $tempResult = $this->validateInternal(
96
                $validatedData,
97
                $attributeRules,
98
                $validatedContext
99
            );
100
101 94
            $result = $this->addErrors($result, $tempResult->getErrors());
102 94
            $results[] = $result;
103
        }
104
105 104
        foreach ($results as $result) {
106 94
            $compoundResult = $this->addErrors($compoundResult, $result->getErrors());
107
        }
108
109 104
        if ($data instanceof PostValidationHookInterface) {
110
            $data->processValidationResult($compoundResult);
111
        }
112
113 104
        return $compoundResult;
114
    }
115
116 109
    #[Pure]
117
    private function normalizeDataSet($data): DataSetInterface
118
    {
119 109
        if ($data instanceof DataSetInterface) {
120 47
            return $data;
121
        }
122
123 67
        if (is_object($data)) {
124 27
            return new ObjectDataSet($data);
125
        }
126
127 44
        if (is_array($data)) {
128 15
            return new ArrayDataSet($data);
129
        }
130
131 39
        return new MixedDataSet($data);
132
    }
133
134
    /**
135
     * @param $value
136
     * @param iterable<Closure|Closure[]|RuleInterface|RuleInterface[]> $rules
137
     * @param ValidationContext $context
138
     *
139
     * @throws ContainerExceptionInterface
140
     * @throws NotFoundExceptionInterface
141
     *
142
     * @return Result
143
     */
144 99
    private function validateInternal($value, iterable $rules, ValidationContext $context): Result
145
    {
146 99
        $compoundResult = new Result();
147 99
        foreach ($rules as $rule) {
148 99
            if ($rule instanceof BeforeValidationInterface) {
149 96
                $preValidateResult = $this->preValidate($value, $context, $rule);
150 96
                if ($preValidateResult) {
151 15
                    continue;
152
                }
153
            }
154
155 94
            $ruleHandler = $this->ruleHandlerResolver->resolve($rule->getHandlerClassName());
156 92
            $ruleResult = $ruleHandler->validate($value, $rule, $context);
157 89
            if ($ruleResult->isValid()) {
158 36
                continue;
159
            }
160
161 73
            $context->setParameter($this->parameterPreviousRulesErrored, true);
162
163 73
            foreach ($ruleResult->getErrors() as $error) {
164 73
                $valuePath = $error->getValuePath();
165 73
                if ($context->getAttribute() !== null) {
166 52
                    $valuePath = [$context->getAttribute(), ...$valuePath];
167
                }
168 73
                $compoundResult->addError($error->getMessage(), $valuePath);
169
            }
170
        }
171 94
        return $compoundResult;
172
    }
173
174
    /**
175
     * @param array $rules
176
     *
177
     * @return iterable<RuleInterface>
178
     */
179 99
    private function normalizeRules(iterable $rules): iterable
180
    {
181 99
        foreach ($rules as $rule) {
182 99
            yield $this->normalizeRule($rule);
183
        }
184
    }
185
186 99
    private function normalizeRule($rule): RuleInterface
187
    {
188 99
        if (is_callable($rule)) {
189 3
            return new Callback($rule);
190
        }
191
192 99
        if (!$rule instanceof RuleInterface) {
193
            throw new InvalidArgumentException(
194
                sprintf(
195
                    'Rule should be either an instance of %s or a callable, %s given.',
196
                    RuleInterface::class,
197
                    gettype($rule)
198
                )
199
            );
200
        }
201
202 99
        if ($rule instanceof SkipOnEmptyInterface && $rule->getSkipOnEmpty() === null) {
203 94
            $rule = $rule->skipOnEmpty($this->defaultSkipOnEmptyCallback);
204
        }
205
206 99
        return $rule;
207
    }
208
209 94
    private function addErrors(Result $result, array $errors): Result
210
    {
211 94
        foreach ($errors as $error) {
212 73
            $result->addError($error->getMessage(), $error->getValuePath());
213
        }
214 94
        return $result;
215
    }
216
}
217