Passed
Pull Request — master (#364)
by Alexander
03:08
created

EachHandler::validate()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 47
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 8.2327

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 25
c 4
b 1
f 0
dl 0
loc 47
ccs 22
cts 26
cp 0.8462
rs 8.4444
cc 8
nc 6
nop 3
crap 8.2327
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Closure;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\RuleInterface;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function is_int;
15
16
/**
17
 * Validates an array by checking each of its elements against a set of rules.
18
 */
19
final class EachHandler implements RuleHandlerInterface
20
{
21 10
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
22
    {
23 10
        if (!$rule instanceof Each) {
24 1
            throw new UnexpectedRuleException(Each::class, $rule);
25
        }
26
27 9
        $rules = $rule->getRules();
28
29 9
        $result = new Result();
30 9
        if (!is_iterable($value)) {
31 1
            $result->addError($rule->getIncorrectInputMessage(), [
32 1
                'attribute' => $context->getAttribute(),
33 1
                'valueType' => get_debug_type($value),
34
            ]);
35
36 1
            return $result;
37
        }
38
39
        /** @var mixed $item */
40 8
        foreach ($value as $index => $item) {
41 8
            if (!is_int($index)) {
42
                $result->addError($rule->getIncorrectInputMessage(), [
43
                    'attribute' => $context->getAttribute(),
44
                    'valueType' => get_debug_type($value),
45
                ]);
46
47
                return $result;
48
            }
49
50
            /** @var array<mixed, Closure|Closure[]|RuleInterface|RuleInterface[]> $relatedRule */
51 8
            $relatedRule = [$index => $rules];
52
53 8
            $itemResult = $context->getValidator()->validate($item, $relatedRule);
54 8
            if ($itemResult->isValid()) {
55 7
                continue;
56
            }
57
58 7
            foreach ($itemResult->getErrors() as $error) {
59 7
                $result->addError(
60 7
                    $error->getMessage(),
61 7
                    $error->getParameters(),
62 7
                    $error->getValuePath() === [] ? [$index] : [$index, ...$error->getValuePath()],
63
                );
64
            }
65
        }
66
67 8
        return $result;
68
    }
69
}
70