Passed
Pull Request — master (#222)
by Alexander
05:06 queued 02:29
created

EachValidator::validate()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.3541

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
c 1
b 0
f 0
nc 5
nop 4
dl 0
loc 25
ccs 11
cts 14
cp 0.7856
crap 6.3541
rs 9.2222
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