Passed
Pull Request — master (#219)
by
unknown
02:40
created

Each::validateValue()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 8.1867

Importance

Changes 0
Metric Value
cc 8
eloc 22
c 0
b 0
f 0
nc 5
nop 2
dl 0
loc 38
ccs 18
cts 21
cp 0.8571
crap 8.1867
rs 8.4444
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use InvalidArgumentException;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\Rule;
12
use Yiisoft\Validator\RuleSet;
13
use Yiisoft\Validator\ValidationContext;
14
use function is_array;
15
use function is_iterable;
16
17
/**
18
 * Validates an array by checking each of its elements against a set of rules.
19
 */
20
#[Attribute(Attribute::TARGET_PROPERTY)]
21
final class Each extends Rule
22
{
23
    private ?RuleSet $ruleSet = null;
24
25 6
    public function __construct(
26
        iterable $rules = [],
27
        private string $incorrectInputMessage = 'Value should be array or iterable.',
28
        private string $message = '{error} {value} given.',
29
        ?FormatterInterface $formatter = null,
30
        bool $skipOnEmpty = false,
31
        bool $skipOnError = false,
32
        $when = null,
33
    ) {
34 6
        if ($rules !== []) {
35 6
            $this->ruleSet = new RuleSet($rules);
36
        }
37
38 6
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
39
    }
40
41
    /**
42
     * @see $message
43
     */
44
    public function message(string $value): self
45
    {
46
        $new = clone $this;
47
        $new->message = $value;
48
49
        return $new;
50
    }
51
52
    /**
53
     * @see $incorrectInputMessage
54
     */
55
    public function incorrectInputMessage(string $value): self
56
    {
57
        $new = clone $this;
58
        $new->incorrectInputMessage = $value;
59
60
        return $new;
61
    }
62
63 3
    protected function validateValue($value, ?ValidationContext $context = null): Result
64
    {
65 3
        if ($this->ruleSet === null) {
66
            throw new InvalidArgumentException('Rules are required.');
67
        }
68
69 3
        $result = new Result();
70 3
        if (!is_iterable($value)) {
71
            $result->addError($this->incorrectInputMessage);
72
73
            return $result;
74
        }
75
76 3
        foreach ($value as $index => $item) {
77 3
            $itemResult = $this->ruleSet->validate($item, $context);
78 3
            if ($itemResult->isValid()) {
79 2
                continue;
80
            }
81
82 3
            foreach ($itemResult->getErrors() as $error) {
83 3
                if (!is_array($item)) {
84 3
                    $errorKey = [$index];
85 3
                    $formatMessage = true;
86
                } else {
87 1
                    $errorKey = [$index, ...$error->getValuePath()];
88 1
                    $formatMessage = false;
89
                }
90
91 3
                $message = !$formatMessage ? $error->getMessage() : $this->formatMessage($this->message, [
92 3
                    'error' => $error->getMessage(),
93
                    'value' => $item,
94
                ]);
95
96 3
                $result->addError($message, $errorKey);
97
            }
98
        }
99
100 3
        return $result;
101
    }
102
103 2
    public function getOptions(): array
104
    {
105 2
        return $this->ruleSet->asArray();
0 ignored issues
show
Bug introduced by
The method asArray() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

105
        return $this->ruleSet->/** @scrutinizer ignore-call */ asArray();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
106
    }
107
}
108