Passed
Pull Request — master (#41)
by Alexander
12:52 queued 06:33
created

Each::validateValue()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

Changes 0
Metric Value
cc 5
eloc 12
c 0
b 0
f 0
nc 5
nop 2
dl 0
loc 21
ccs 12
cts 13
cp 0.9231
crap 5.0113
rs 9.5555
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 1
    public function __construct(Rules $rules)
20
    {
21 1
        $this->rules = $rules;
22
    }
23
24 1
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
25
    {
26 1
        $result = new Result();
27 1
        if (!is_iterable($value)) {
28
            return $result->addError($this->incorrectInputMessage);
29
        }
30
31 1
        foreach ($value as $item) {
32 1
            $itemResult = $this->rules->validate($item, $dataSet);
33 1
            if ($itemResult->isValid() === false) {
34 1
                foreach ($itemResult->getErrors() as $error) {
35 1
                    $message = $this->formatMessage($this->message, [
36 1
                        'error' => $error,
37 1
                        'value' => $item,
38
                    ]);
39 1
                    $result = $result->addError($message);
40
                }
41
            }
42
        }
43
44 1
        return $result;
45
    }
46
}
47