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

Each::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 7
dl 0
loc 10
ccs 2
cts 2
cp 1
crap 1
rs 10
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