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

Validator::validate()   F

Complexity

Conditions 16
Paths 280

Size

Total Lines 70
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 16.5393

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 40
c 3
b 0
f 0
dl 0
loc 70
ccs 34
cts 39
cp 0.8718
rs 3.7333
cc 16
nc 280
nop 2
crap 16.5393

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
40 695
    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
        bool|callable|null $defaultSkipOnEmpty = null,
51
    ) {
52 695
        $this->defaultSkipOnEmptyCallback = SkipOnEmptyNormalizer::normalize($defaultSkipOnEmpty);
53
    }
54
55
    /**
56
     * @param DataSetInterface|mixed|RulesProviderInterface $data
57
     * @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...
58
     *
59
     * @throws ContainerExceptionInterface
60
     * @throws NotFoundExceptionInterface
61
     */
62 715
    public function validate(mixed $data, iterable|object|string|null $rules = null): Result
63
    {
64 715
        $data = $this->normalizeDataSet($data);
65 715
        if ($rules === null && $data instanceof RulesProviderInterface) {
66 27
            $rules = $data->getRules();
67 692
        } elseif ($rules instanceof RulesProviderInterface) {
68 2
            $rules = $rules->getRules();
69 690
        } elseif ($rules instanceof RuleInterface) {
70 1
            $rules = [$rules];
71 689
        } elseif (!$rules instanceof Traversable && !is_array($rules) && $rules !== null) {
72
            $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

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