Completed
Push — master ( 296743...12eab9 )
by Kirill
36:17
created

Factory::addValidator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 4
cts 6
cp 0.6667
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.1481
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\SDL\Reflection\Validation\Base;
11
12
/**
13
 * Class Factory
14
 */
15
class Factory extends BaseValidator
16
{
17
    /**
18
     * @var array|ValidatorInterface[]
19
     */
20
    private $items = [];
21
22
    /**
23
     * @var \Closure|null
24
     */
25
    private $matcher;
26
27
    /**
28
     * @param \Closure $matcher
29
     * @return Factory
30
     */
31 283
    public function setMatcher(\Closure $matcher): self
32
    {
33 283
        $this->matcher = $matcher;
34
35 283
        return $this;
36
    }
37
38
    /**
39
     * @param string $item
40
     * @return Factory
41
     * @throws \InvalidArgumentException
42
     * @throws \OutOfBoundsException
43
     */
44 283
    public function addValidator(string $item): self
45
    {
46 283
        if (! \is_subclass_of($item, ValidatorInterface::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Railt\SDL\Reflection\Va...lidatorInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
47
            $error = \sprintf('%s must be instance of %s', $item, ValidatorInterface::class);
48
            throw new \InvalidArgumentException($error);
49
        }
50
51 283
        $this->items[] = new $item($this->validator, $this->getCallStack(), $this->getGroupName());
52
53 283
        return $this;
54
    }
55
56
    /**
57
     * @param array ...$args
58
     * @return void
59
     * @internal Delegate
60
     */
61 6576
    public function validate(...$args): void
62
    {
63 6576
        foreach ($this->items as $item) {
64 6576
            if ($this->match($item, ...$args)) {
65 6576
                $item->validate(...$args);
66
            }
67
        }
68 6576
    }
69
70
    /**
71
     * @param ValidatorInterface $validator
72
     * @param array ...$args
73
     * @return bool
74
     */
75 6576
    private function match(ValidatorInterface $validator, ...$args): bool
76
    {
77 6576
        if ($this->matcher !== null) {
78 6576
            return ($this->matcher)($validator, ...$args);
79
        }
80
81
        return true;
82
    }
83
}
84