Passed
Pull Request — master (#222)
by Dmitriy
12:29
created

EachHandler::validate()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 36
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7.2694

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 36
ccs 14
cts 17
cp 0.8235
rs 8.8333
c 0
b 0
f 0
cc 7
nc 6
nop 4
crap 7.2694
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\Rule\RuleHandlerInterface;
10
use Yiisoft\Validator\RuleInterface;
11
use Yiisoft\Validator\ValidationContext;
12
use Yiisoft\Validator\ValidatorInterface;
13
use Yiisoft\Validator\Exception\UnexpectedRuleException;
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 4
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
21
    {
22 4
        if (!$rule instanceof Each) {
23 1
            throw new UnexpectedRuleException(Each::class, $rule);
24
        }
25
26
        /**
27
         * @var iterable<RuleInterface> $rules
28
         */
29 3
        $rules = $rule->rules;
30 3
        if ($rules === []) {
31
            throw new InvalidArgumentException('Rules are required.');
32
        }
33
34 3
        $result = new Result();
35 3
        if (!is_iterable($value)) {
36
            $result->addError($rule->incorrectInputMessage);
37
38
            return $result;
39
        }
40
41 3
        foreach ($value as $index => $item) {
42
            /**
43
             * @psalm-suppress InvalidArgument
44
             */
45 3
            $itemResult = $validator->validate($item, [$index => $rules]);
46 3
            if ($itemResult->isValid()) {
47 3
                continue;
48
            }
49
50 2
            foreach ($itemResult->getErrors() as $error) {
51 2
                $result->mergeError($error);
52
            }
53
        }
54
55 3
        return $result;
56
    }
57
}
58