Passed
Pull Request — master (#364)
by
unknown
03:12
created

EachHandler   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 95.24%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 21
c 2
b 0
f 0
dl 0
loc 38
ccs 20
cts 21
cp 0.9524
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 36 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Closure;
8
use InvalidArgumentException;
9
use Yiisoft\Validator\Exception\UnexpectedRuleException;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\RuleHandlerInterface;
12
use Yiisoft\Validator\RuleInterface;
13
use Yiisoft\Validator\ValidationContext;
14
15
/**
16
 * Validates an array by checking each of its elements against a set of rules.
17
 */
18
final class EachHandler implements RuleHandlerInterface
19
{
20 10
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
21
    {
22 10
        if (!$rule instanceof Each) {
23 1
            throw new UnexpectedRuleException(Each::class, $rule);
24
        }
25
26 9
        $rules = $rule->getRules();
27 9
        if ($rules === []) {
28
            throw new InvalidArgumentException('Rules are required.');
29
        }
30
31 9
        $result = new Result();
32 9
        if (!is_iterable($value)) {
33 1
            $result->addError($rule->getIncorrectInputMessage());
34
35 1
            return $result;
36
        }
37
38 8
        foreach ($value as $index => $item) {
39
            /** @var array<mixed, Closure|Closure[]|RuleInterface|RuleInterface[]> $rule */
40 8
            $rule = [$index => $rules];
41 8
            $itemResult = $context->getValidator()->validate($item, $rule);
42 8
            if ($itemResult->isValid()) {
43 7
                continue;
44
            }
45
46 7
            foreach ($itemResult->getErrors() as $error) {
47 7
                $result->addError(
48 7
                    $error->getMessage(),
49 7
                    $error->getParameters(),
50 7
                    $error->getValuePath() === [] ? [$index] : [$index, ...$error->getValuePath()],
51
                );
52
            }
53
        }
54
55 8
        return $result;
56
    }
57
}
58