ArrayEachValidator::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 0
cts 7
cp 0
rs 10
cc 2
nc 2
nop 1
crap 6
1
<?php declare(strict_types=1);
2
3
namespace indigerd\scenarios\validation\validator;
4
5
class ArrayEachValidator extends ArrayValidator
6
{
7
    protected $validator;
8
9
    public function __construct(array $params = [])
10
    {
11
        parent::__construct($params);
12
        if (!($this->validator instanceof ValidatorInterface)) {
13
            throw new \InvalidArgumentException('Invalid validator param value');
14
        }
15
    }
16
17
    public function setValidator(ValidatorInterface $validator) : self
18
    {
19
        $this->validator = $validator;
20
        return $this;
21
    }
22
23
    public function validate($value, array $context = []): bool
24
    {
25
        if ($this->skipOnEmpty and empty($value)) {
26
            return true;
27
        }
28
        $valid = parent::validate($value, $context);
29
        if (!$valid) {
30
            return false;
31
        }
32
        foreach ($value as $v) {
33
            if ($this->skipOnEmpty and empty($v)) {
34
                continue;
35
            }
36
            $valid = $this->validator->validate($v, $context);
37
            if (false === $valid) {
38
                $this->message = $this->validator->getMessage();
39
                return false;
40
            }
41
        }
42
        return true;
43
    }
44
}
45