Passed
Pull Request — master (#222)
by Alexander
04:47 queued 02:23
created

EachValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 78.56%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 27
ccs 11
cts 14
cp 0.7856
rs 10
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 25 6
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\RuleValidatorInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
13
/**
14
 * Validates an array by checking each of its elements against a set of rules.
15
 */
16
final class EachValidator implements RuleValidatorInterface
17
{
18 3
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
19
    {
20 3
        if ($rule->rules === null) {
21
            throw new InvalidArgumentException('Rules are required.');
22
        }
23
24 3
        $result = new Result();
25 3
        if (!is_iterable($value)) {
26
            $result->addError($rule->incorrectInputMessage);
27
28
            return $result;
29
        }
30
31 3
        foreach ($value as $index => $item) {
32 3
            $itemResult = $validator->validate($item, [$index => $rule->rules]);
33 3
            if ($itemResult->isValid()) {
34 3
                continue;
35
            }
36
37 2
            foreach ($itemResult->getErrors() as $error) {
38 2
                $result->merge($error);
39
            }
40
        }
41
42 3
        return $result;
43
    }
44
}
45