Passed
Push — master ( fdfcd6...00fdb7 )
by Flo
02:01
created

ValidatorChain::getValidators()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Class ValidatorChain | ValidatorChain.php
4
 * @package Form\Validator
5
 * @author  Florian Knapp <[email protected]>
6
 */
7
namespace Faulancer\Form\Validator;
8
9
use Faulancer\Form\Type\AbstractType;
10
11
/**
12
 * Class ValidatorChain
13
 */
14
class ValidatorChain
15
{
16
17
    /** @var AbstractValidator[] */
18
    protected $validators = [];
19
20
    /** @var array */
21
    protected $messages = [];
22
23
    /** @var AbstractType|null */
24
    protected $field = null;
25
26
    /**
27
     * ValidatorChain constructor.
28
     * @param AbstractType $field
29
     * @codeCoverageIgnore
30
     */
31
    public function __construct(AbstractType $field)
32
    {
33
        $this->field = $field;
34
    }
35
36
    /**
37
     * @param AbstractValidator $validator
38
     * @codeCoverageIgnore
39
     */
40
    public function add(AbstractValidator $validator)
41
    {
42
        $this->validators[] = $validator;
43
    }
44
45
    /**
46
     * @return AbstractValidator[]
47
     * @codeCoverageIgnore
48
     */
49
    public function getValidators(): array
50
    {
51
        return $this->validators;
52
    }
53
54
    /**
55
     * @return boolean
56
     * @codeCoverageIgnore
57
     */
58
    public function validate() :bool
59
    {
60
        foreach ($this->validators as $validator) {
61
62
            $result = $validator->process($this->field->getValue());
63
64
            if (!$result) {
65
                $this->messages[] = $validator->getMessage();
66
            }
67
68
        }
69
70
        if (!empty($this->messages)) {
71
            // Access first one because every validator can return its field object
72
            $this->validators[0]->getField()->setErrorMessages($this->messages);
73
            $this->validators[0]->getField()->addAttribute('class', 'error');
74
            return false;
75
        }
76
77
        return true;
78
    }
79
80
}