Passed
Push — master ( 0f05d2...660106 )
by Alexander
08:58
created

Each::validateValue()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0729

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 5
nop 2
dl 0
loc 22
ccs 12
cts 14
cp 0.8571
crap 5.0729
rs 9.5222
c 0
b 0
f 0
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