Test Failed
Pull Request — master (#19)
by Flo
02:48
created

ValidatorChain   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 58
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 21 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
    /** @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 boolean
47
     * @codeCoverageIgnore
48
     */
49
    public function validate() :bool
50
    {
51
        foreach ($this->validators as $validator) {
52
53
            $result = $validator->process($this->field->getValue());
54
55
            if (!$result) {
56
                $this->messages[] = $validator->getMessage();
57
            }
58
59
        }
60
61
        if (!empty($this->messages)) {
62
            // Access first one because every validator can return its field object
63
            $this->validators[0]->getField()->setErrorMessages($this->messages);
64
            $this->validators[0]->getField()->addAttribute('class', 'error');
65
            return false;
66
        }
67
68
        return true;
69
    }
70
71
}