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

EachValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 81.25%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 16
c 2
b 0
f 0
dl 0
loc 31
ccs 13
cts 16
cp 0.8125
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 29 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Each;
6
7
use InvalidArgumentException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\AtLeast\AtLeast;
10
use Yiisoft\Validator\Rule\RuleValidatorInterface;
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 EachValidator implements RuleValidatorInterface
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 3
        if ($rule->rules === null) {
27
            throw new InvalidArgumentException('Rules are required.');
28
        }
29
30 3
        $result = new Result();
31 3
        if (!is_iterable($value)) {
32
            $result->addError($rule->incorrectInputMessage);
33
34
            return $result;
35
        }
36
37 3
        foreach ($value as $index => $item) {
38 3
            $itemResult = $validator->validate($item, [$index => $rule->rules]);
39 3
            if ($itemResult->isValid()) {
40 3
                continue;
41
            }
42
43 2
            foreach ($itemResult->getErrors() as $error) {
44 2
                $result->merge($error);
45
            }
46
        }
47
48 3
        return $result;
49
    }
50
}
51