Passed
Pull Request — master (#222)
by Dmitriy
02:23
created

EachHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 82.35%

Importance

Changes 0
Metric Value
wmc 7
eloc 17
dl 0
loc 38
ccs 14
cts 17
cp 0.8235
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 36 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use InvalidArgumentException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use Yiisoft\Validator\Exception\UnexpectedRuleException;
13
14
/**
15
 * Validates an array by checking each of its elements against a set of rules.
16
 */
17
final class EachHandler implements RuleHandlerInterface
18
{
19 4
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
20
    {
21 4
        if (!$rule instanceof Each) {
22 1
            throw new UnexpectedRuleException(Each::class, $rule);
23
        }
24
25
        /**
26
         * @var iterable<RuleInterface> $rules
27
         */
28 3
        $rules = $rule->rules;
29 3
        if ($rules === []) {
30
            throw new InvalidArgumentException('Rules are required.');
31
        }
32
33 3
        $result = new Result();
34 3
        if (!is_iterable($value)) {
35
            $result->addError($rule->incorrectInputMessage);
36
37
            return $result;
38
        }
39
40 3
        foreach ($value as $index => $item) {
41
            /**
42
             * @psalm-suppress InvalidArgument
43
             */
44 3
            $itemResult = $context->getValidator()->validate($item, [$index => $rules]);
0 ignored issues
show
Bug introduced by
The method getValidator() does not exist on null. ( Ignorable by Annotation )

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

44
            $itemResult = $context->/** @scrutinizer ignore-call */ getValidator()->validate($item, [$index => $rules]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
45 3
            if ($itemResult->isValid()) {
46 3
                continue;
47
            }
48
49 2
            foreach ($itemResult->getErrors() as $error) {
50 2
                $result->mergeError($error);
51
            }
52
        }
53
54 3
        return $result;
55
    }
56
}
57