Completed
Push — master ( 6630f6...b334d3 )
by Albert
05:18
created

Validator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 83
rs 10
c 1
b 0
f 0
ccs 23
cts 23
cp 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 4 1
A getFields() 0 4 1
A merge() 0 8 2
A addRawField() 0 11 2
A addField() 0 4 1
A validate() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Albert221\Validation;
6
7
use InvalidArgumentException;
8
9
class Validator
10
{
11
    /**
12
     * @var Field[]
13
     */
14
    private $fields = [];
15
16
    /**
17
     * @return Validator
18
     */
19
    public static function build()
20
    {
21
        return new self();
22
    }
23 8
24
    /**
25 8
     * @return Field[]
26 1
     */
27 1
    public function getFields(): array
28 1
    {
29
        return $this->fields;
30
    }
31 7
32 1
    /**
33
     * @param Validator $validatorBuilder
34
     *
35 7
     * @return Validator
36
     */
37 7
    public function merge(Validator $validatorBuilder): self
38 1
    {
39 1
        foreach ($validatorBuilder->getFields() as $field) {
40 7
            $this->addRawField($field);
41
        }
42
43
        return $this;
44
    }
45
46
    /**
47
     * @param Field $field
48 7
     *
49
     * @return Field
50 7
     */
51
    public function addRawField(Field $field)
52
    {
53
        if (array_key_exists($field->getName(), $this->fields)) {
54
            throw new InvalidArgumentException(sprintf(
55
                'Field with name "%s" already exists.',
56
                $field->getName()
57
            ));
58
        }
59
60 4
        return $this->fields[$field->getName()] = $field;
61
    }
62 4
63
    /**
64 4
     * @param string $name
65
     *
66
     * @return Field
67
     */
68
    public function addField(string $name): Field
69
    {
70
        return $this->addRawField(new Field($name, $this));
71
    }
72 3
73
    /**
74
     * @param $data
75 3
     *
76 3
     * @return ValidationState
77
     */
78 3
    public function validate($data): ValidationState
79
    {
80
        $verdicts = [];
81
        foreach ($this->fields as $field) {
82
            $value = $data[$field->getName()] ?? null;
83
84
            foreach ($field->getRules() as $rule) {
85
                $verdicts[] = $rule->verdict($value);
86 4
            }
87
        }
88 4
89
        return new ValidationState($verdicts);
90
    }
91
}
92