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

Each   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 34
ccs 14
cts 16
cp 0.875
rs 10
c 0
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validateValue() 0 22 5
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