Test Failed
Pull Request — master (#175)
by
unknown
05:56 queued 03:39
created

Each::validateValue()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7.0572

Importance

Changes 0
Metric Value
cc 7
eloc 20
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 33
ccs 17
cts 19
cp 0.8947
crap 7.0572
rs 8.6666
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
    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 7
        $when = null,
26
    ) {
27 7
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
28 7
    }
29 7
30
    protected function validateValue($value, ?ValidationContext $context = null): Result
31
    {
32 4
        $result = new Result();
33
        if (!is_iterable($value)) {
34 4
            $result->addError($this->incorrectInputMessage);
35 4
            return $result;
36
        }
37
38
        foreach ($value as $index => $item) {
39
            $itemResult = $this->ruleSet->validate($item, $context);
40 4
            if ($itemResult->isValid()) {
41 4
                continue;
42 4
            }
43 3
44
            foreach ($itemResult->getErrors() as $error) {
45
                if (!is_array($item)) {
46 4
                    $errorKey = [$index];
47 4
                    $formatMessage = true;
48 4
                } else {
49 4
                    $errorKey = [$index, ...$error->getValuePath()];
50
                    $formatMessage = false;
51 1
                }
52 1
53
                $message = !$formatMessage ? $error->getMessage() : $this->formatMessage($this->message, [
54
                    'error' => $error->getMessage(),
55 4
                    'value' => $item,
56 4
                ]);
57 4
58
                $result->addError($message, $errorKey);
59
            }
60 4
        }
61
62
        return $result;
63
    }
64 4
65
    public function getOptions(): array
66
    {
67
        return $this->ruleSet->asArray();
68
    }
69
}
70