Passed
Push — master ( 99ab46...a20a6f )
by Alexander
02:59
created

Each::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
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 1
dl 0
loc 3
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\HasValidationErrorMessage;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\Rules;
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
class Each extends Rule
17
{
18
    use HasValidationErrorMessage;
19
20
    private Rules $rules;
21
22
    private string $incorrectInputMessage = 'Value should be array or iterable';
23
    private string $message = '{error} {value} given.';
24
25 4
    public static function rule(Rules $rules): self
26
    {
27 4
        $rule = new self();
28 4
        $rule->rules = $rules;
29 4
        return $rule;
30
    }
31
32 1
    protected function validateValue($value, ValidationContext $context = null): Result
33
    {
34 1
        $result = new Result();
35 1
        if (!is_iterable($value)) {
36
            $result->addError($this->incorrectInputMessage);
37
            return $result;
38
        }
39
40 1
        foreach ($value as $item) {
41 1
            $itemResult = $this->rules->validate($item, $context);
42 1
            if ($itemResult->isValid() === false) {
43 1
                foreach ($itemResult->getErrors() as $error) {
44 1
                    $result->addError(
45 1
                        $this->formatMessage(
46 1
                            $this->message,
47
                            [
48 1
                                'error' => $error,
49 1
                                'value' => $item,
50
                            ]
51
                        )
52
                    );
53
                }
54
            }
55
        }
56
57 1
        return $result;
58
    }
59
60
    public function incorrectInputMessage(string $message): self
61
    {
62
        $new = clone $this;
63
        $new->incorrectInputMessage = $message;
64
        return $new;
65
    }
66
67 2
    public function getOptions(): array
68
    {
69 2
        return $this->rules->asArray();
70
    }
71
}
72