Completed
Push — master ( 91b98b...104eec )
by Albert
14s
created

Validator::getFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 1
eloc 2
nc 1
nop 0
crap 1
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 3
    public static function build()
20
    {
21 3
        return new self();
22
    }
23
24
    /**
25
     * @return Field[]
26
     */
27 3
    public function getFields(): array
28
    {
29 3
        return $this->fields;
30
    }
31
32
    /**
33
     * @param Validator $validatorBuilder
34
     *
35
     * @return Validator
36
     */
37 1
    public function merge(Validator $validatorBuilder): self
38
    {
39 1
        foreach ($validatorBuilder->getFields() as $field) {
40 1
            $this->addRawField($field);
41
        }
42
43 1
        return $this;
44
    }
45
46
    /**
47
     * @param Field $field
48
     *
49
     * @return Field
50
     */
51 7
    public function addRawField(Field $field)
52
    {
53 7
        if (array_key_exists($field->getName(), $this->fields)) {
54 1
            throw new InvalidArgumentException(sprintf(
55 1
                'Field with name "%s" already exists.',
56 1
                $field->getName()
57
            ));
58
        }
59
60 7
        return $this->fields[$field->getName()] = $field;
61
    }
62
63
    /**
64
     * @param string $name
65
     *
66
     * @return Field
67
     */
68 5
    public function addField(string $name): Field
69
    {
70 5
        return $this->addRawField(new Field($name, $this));
71
    }
72
73
    /**
74
     * @param $data
75
     *
76
     * @return VerdictList
77
     */
78 3
    public function validate($data): VerdictList
79
    {
80 3
        $verdicts = [];
81 3
        foreach ($this->fields as $field) {
82 3
            $value = $data[$field->getName()] ?? null;
83
84 3
            foreach ($field->getRules() as $rule) {
85 3
                $verdicts[] = $rule->verdict($value);
86
            }
87
        }
88
89 3
        return new VerdictList($verdicts);
90
    }
91
}
92