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

ValidatorChain   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 48
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A add() 0 4 1
A validate() 0 19 4
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
}