Completed
Pull Request — master (#19)
by Flo
04:38
created

ValidatorChain::validate()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 6
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
    protected $messages = [];
21
22
    /** @var AbstractType|null */
23
    protected $field = null;
24
25
    public function __construct(AbstractType $field)
26
    {
27
        $this->field = $field;
28
    }
29
30
    /**
31
     * @param AbstractValidator $validator
32
     */
33
    public function add(AbstractValidator $validator)
34
    {
35
        $this->validators[] = $validator;
36
    }
37
38
    /**
39
     * @return boolean
40
     */
41
    public function validate() :bool
42
    {
43
        foreach ($this->validators as $validator) {
44
45
            $result = $validator->process($this->field->getValue());
46
47
            if (!$result) {
48
                $this->messages[] = $validator->getMessage();
49
            }
50
51
        }
52
53
        if (!empty($this->messages)) {
54
            $this->validators[0]->getField()->setErrorMessages($this->messages);
55
            return false;
56
        }
57
58
        return true;
59
    }
60
61
}