Passed
Push — master ( 0f05d2...660106 )
by Alexander
08:58
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
namespace Yiisoft\Validator\Rule;
4
5
use Yiisoft\Validator\DataSetInterface;
6
use Yiisoft\Validator\Result;
7
use Yiisoft\Validator\Rule;
8
use Yiisoft\Validator\Rules;
9
10
/**
11
 * Each validator validates an array by checking each of its elements against a set of rules
12
 */
13
class Each extends Rule
14
{
15
    private Rules $rules;
16
17
    private string $incorrectInputMessage = 'Value should be array or iterable';
18
    private string $message = '{error} {value} given.';
19
20 1
    public function __construct(Rules $rules)
21
    {
22 1
        $this->rules = $rules;
23
    }
24
25 1
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
26
    {
27 1
        $result = new Result();
28 1
        if (!is_iterable($value)) {
29
            $result->addError($this->incorrectInputMessage);
30
            return $result;
31
        }
32
33 1
        foreach ($value as $item) {
34 1
            $itemResult = $this->rules->validate($item, $dataSet);
35 1
            if ($itemResult->isValid() === false) {
36 1
                foreach ($itemResult->getErrors() as $error) {
37 1
                    $message = $this->formatMessage($this->message, [
38 1
                        'error' => $error,
39 1
                        'value' => $item,
40
                    ]);
41 1
                    $result->addError($message);
42
                }
43
            }
44
        }
45
46 1
        return $result;
47
    }
48
}
49