Test Failed
Pull Request — master (#364)
by
unknown
02:49
created

Validator::validate()   F

Complexity

Conditions 16
Paths 280

Size

Total Lines 68
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 16.0345

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 40
c 3
b 0
f 0
dl 0
loc 68
ccs 37
cts 39
cp 0.9487
rs 3.7333
cc 16
nc 280
nop 2
crap 16.0345

How to fix   Long Method    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\Translator\TranslatorInterface;
15
use Yiisoft\Validator\DataSet\ArrayDataSet;
16
use Yiisoft\Validator\DataSet\ObjectDataSet;
17
use Yiisoft\Validator\DataSet\SingleValueDataSet;
18
use Yiisoft\Validator\Rule\Callback;
19
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
20
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
21
22
use function is_array;
23
use function is_callable;
24
use function is_int;
25
use function is_object;
26
use function is_string;
27
28
/**
29
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
30
 */
31
final class Validator implements ValidatorInterface
32
{
33
    use PreValidateTrait;
34
35
    /**
36
     * @var callable
37
     */
38
    private $defaultSkipOnEmptyCallback;
39 680
40
    public function __construct(
41
        private RuleHandlerResolverInterface $ruleHandlerResolver,
42
        private TranslatorInterface $translator,
43
        /**
44
         * @var int What visibility levels to use when reading rules from the class specified in `$rules` argument in
45
         * {@see validate()} method.
46
         */
47
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
48
        | ReflectionProperty::IS_PROTECTED
49
        | ReflectionProperty::IS_PUBLIC,
50
51
        /**
52
         * @var bool|callable|null
53
         */
54
        bool|callable|null $defaultSkipOnEmpty = null,
55 680
    ) {
56
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
57
    }
58
59
    /**
60
     * @param DataSetInterface|mixed|RulesProviderInterface $data
61
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|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[]>|RuleInterface|RulesProviderInterface|null.
Loading history...
62
     *
63
     * @throws ContainerExceptionInterface
64
     * @throws NotFoundExceptionInterface
65 700
     */
66
    public function validate(mixed $data, iterable|object|string|null $rules = null): Result
67 700
    {
68 700
        $data = $this->normalizeDataSet($data);
69 27
        if ($rules === null && $data instanceof RulesProviderInterface) {
70 677
            $rules = $data->getRules();
71 2
        } elseif ($rules instanceof RulesProviderInterface) {
72 675
            $rules = $rules->getRules();
73 1
        } elseif ($rules instanceof RuleInterface) {
74 674
            $rules = [$rules];
75
        } elseif (!$rules instanceof Traversable && !is_array($rules) && $rules !== null) {
76
            $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

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