Passed
Pull Request — master (#41)
by Alexander
19:40 queued 04:42
created

Each   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

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