Passed
Pull Request — master (#99)
by Def
02:50
created

Each::validateValue()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0909

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 5
nop 2
dl 0
loc 21
ccs 11
cts 13
cp 0.8462
crap 5.0909
rs 9.5555
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Translator\TranslatorInterface;
8
use Yiisoft\Validator\DataSetInterface;
9
use Yiisoft\Validator\HasValidationErrorMessage;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\Rule;
12
use Yiisoft\Validator\Rules;
13
14
/**
15
 * Each validator validates an array by checking each of its elements against a set of rules
16
 */
17
class Each extends Rule
18
{
19
    use HasValidationErrorMessage;
20
21
    private Rules $rules;
22
23
    private string $incorrectInputMessage = 'Value should be array or iterable';
24
    private string $message = ' {value} given.';
25
26 4
    public function __construct(Rules $rules)
27
    {
28 4
        $this->rules = $rules;
29 4
    }
30
31 1
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
32
    {
33 1
        $result = new Result();
34 1
        if (!is_iterable($value)) {
35
            $result->addError($this->incorrectInputMessage);
36
            return $result;
37
        }
38
39 1
        foreach ($value as $item) {
40 1
            $itemResult = $this->rules->validate($item, $dataSet);
41 1
            if ($itemResult->isValid() === false) {
42 1
                foreach ($itemResult->getErrors() as $error) {
43 1
                    $result->addError(
44 1
                        $error->message . $this->message,
45 1
                        array_merge(['value' => $item], $error->params)
46
                    );
47
                }
48
            }
49
        }
50
51 1
        return $result;
52
    }
53
54
    public function incorrectInputMessage(string $message): self
55
    {
56
        $new = clone $this;
57
        $new->incorrectInputMessage = $message;
58
        return $new;
59
    }
60
61 2
    public function getOptions(?TranslatorInterface $translator = null): array
62
    {
63 2
        return $this->rules->asArray($translator);
64
    }
65
}
66