Passed
Pull Request — master (#175)
by
unknown
02:31
created

Each   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 91.3%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 52
ccs 21
cts 23
cp 0.913
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getOptions() 0 3 1
A __construct() 0 10 1
B validateValue() 0 33 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\FormatterInterface;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\RuleSet;
11
use Yiisoft\Validator\ValidationContext;
12
13
/**
14
 * Each validator validates an array by checking each of its elements against a set of rules
15
 */
16
final class Each extends Rule
17
{
18 8
    public function __construct(
19
        private RuleSet $ruleSet,
20
        private string $incorrectInputMessage = 'Value should be array or iterable.',
21
        private string $message = '{error} {value} given.',
22
        ?FormatterInterface $formatter = null,
23
        bool $skipOnEmpty = false,
24
        bool $skipOnError = false,
25
        $when = null,
26
    ) {
27 8
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
28
    }
29
30 4
    protected function validateValue($value, ?ValidationContext $context = null): Result
31
    {
32 4
        $result = new Result();
33 4
        if (!is_iterable($value)) {
34
            $result->addError($this->incorrectInputMessage);
35
            return $result;
36
        }
37
38 4
        foreach ($value as $index => $item) {
39 4
            $itemResult = $this->ruleSet->validate($item, $context);
40 4
            if ($itemResult->isValid()) {
41 3
                continue;
42
            }
43
44 4
            foreach ($itemResult->getErrors() as $error) {
45 4
                if (!is_array($item)) {
46 4
                    $errorKey = [$index];
47 4
                    $formatMessage = true;
48
                } else {
49 1
                    $errorKey = [$index, ...$error->getValuePath()];
50 1
                    $formatMessage = false;
51
                }
52
53 4
                $message = !$formatMessage ? $error->getMessage() : $this->formatMessage($this->message, [
54 4
                    'error' => $error->getMessage(),
55
                    'value' => $item,
56
                ]);
57
58 4
                $result->addError($message, $errorKey);
59
            }
60
        }
61
62 4
        return $result;
63
    }
64
65 3
    public function getOptions(): array
66
    {
67 3
        return $this->ruleSet->asArray();
68
    }
69
}
70