Code

< 40 %
40-60 %
> 60 %
1
<?php
2
3
namespace CfdiUtils\Validate;
4
5
use CfdiUtils\Nodes\NodeInterface;
6
use CfdiUtils\Validate\Contracts\ValidatorInterface;
7
use Traversable;
8
9
class MultiValidator implements ValidatorInterface, \Countable, \IteratorAggregate
10
{
11
    /** @var ValidatorInterface[] */
12
    private $validators = [];
13
14
    /** @var string */
15
    private $version;
16
17 34
    public function __construct(string $version)
18
    {
19 34
        $this->version = $version;
20
    }
21
22 26
    public function getVersion(): string
23
    {
24 26
        return $this->version;
25
    }
26
27 25
    public function validate(NodeInterface $comprobante, Asserts $asserts)
28
    {
29 25
        foreach ($this->validators as $validator) {
30 25
            if (! $validator->canValidateCfdiVersion($this->getVersion())) {
31 1
                continue;
32
            }
33 25
            $localAsserts = new Asserts();
34 25
            $validator->validate($comprobante, $localAsserts);
35 25
            $asserts->import($localAsserts);
36 25
            if ($localAsserts->mustStop()) {
37 1
                break;
38
            }
39
        }
40
    }
41
42 3
    public function canValidateCfdiVersion(string $version): bool
43
    {
44 3
        return ($this->version === $version);
45
    }
46
47 23
    public function hydrate(Hydrater $hydrater)
48
    {
49 23
        foreach ($this->validators as $validator) {
50 23
            $hydrater->hydrate($validator);
51
        }
52
    }
53
54
    /*
55
     * Collection methods
56
     */
57
58 33
    public function add(ValidatorInterface $validator)
59
    {
60 33
        $this->validators[] = $validator;
61
    }
62
63 29
    public function addMulti(ValidatorInterface ...$validators)
64
    {
65 29
        foreach ($validators as $validator) {
66 29
            $this->add($validator);
67
        }
68
    }
69
70 2
    public function exists(ValidatorInterface $validator): bool
71
    {
72 2
        return ($this->indexOf($validator) >= 0);
73
    }
74
75 2
    private function indexOf(ValidatorInterface $validator): int
76
    {
77 2
        $index = array_search($validator, $this->validators, true);
78 2
        return (false === $index) ? -1 : (int) $index;
79
    }
80
81 1
    public function remove(ValidatorInterface $validator)
82
    {
83 1
        $index = $this->indexOf($validator);
84 1
        if ($index >= 0) {
85 1
            unset($this->validators[$index]);
86
        }
87
    }
88
89 1
    public function removeAll()
90
    {
91 1
        $this->validators = [];
92
    }
93
94
    /** @return Traversable<ValidatorInterface> */
95 4
    public function getIterator(): Traversable
96
    {
97 4
        return new \ArrayIterator($this->validators);
98
    }
99
100 4
    public function count(): int
101
    {
102 4
        return count($this->validators);
103
    }
104
}
105