Passed
Pull Request — master (#279)
by Alexander
02:41
created

EachHandler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 76.92%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 27
c 1
b 0
f 0
dl 0
loc 50
ccs 20
cts 26
cp 0.7692
rs 10

2 Methods

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