Field::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Albert221\Validation;
6
7
use InvalidArgumentException;
8
9
class Field
10
{
11
    /**
12
     * @var string
13
     */
14
    private $name;
15
16
    /**
17
     * @var Validator
18
     */
19
    private $validator;
20
21
    /**
22
     * @var array Rule\Rule[]
23
     */
24
    private $rules = [];
25
26
    /**
27
     * Field constructor.
28
     *
29
     * @param string $name
30
     * @param Validator $validator
31
     */
32 2
    public function __construct(string $name, Validator $validator)
33
    {
34 2
        $this->name = $name;
35 2
        $this->validator = $validator;
36 2
    }
37
38
    /**
39
     * @return string
40
     */
41 2
    public function getName(): string
42
    {
43 2
        return $this->name;
44
    }
45
46
    /**
47
     * @param string|Rule $rule
48
     * @param array $options
49
     *
50
     * @return Rule
51
     */
52 2
    public function addRule($rule, array $options = []): Rule
53
    {
54 2
        if ($rule instanceof Rule) {
55
            $rule->setValidatorAndField($this->validator, $this);
56
            return $this->rules[] = $rule;
57
        }
58
59 2
        if (!is_subclass_of($rule, Rule::class)) {
60
            throw new InvalidArgumentException(sprintf(
61
                'First argument must be an instance of %s or fully qualified name of this class, %s given.',
62
                Rule::class,
63
                is_scalar($rule) ? gettype($rule) : get_class($rule)
64
            ));
65
        }
66
67
        /** @var Rule $rule */
68 2
        $rule = new $rule($options);
69 2
        $rule->setValidatorAndField($this->validator, $this);
70
71 2
        return $this->rules[] = $rule;
72
    }
73
74
    /**
75
     * @return Rule[]
76
     */
77 2
    public function getRules(): array
78
    {
79 2
        return $this->rules;
80
    }
81
82
    //
83
    // Methods taken from ValidatorBuilder for easy methods chaining.
84
    //
85
86
    /**
87
     * @param string $name
88
     *
89
     * @return Field
90
     */
91 2
    public function addField(string $name): Field
92
    {
93 2
        return $this->validator->addField($name);
94
    }
95
96
    /**
97
     * @param $data
98
     *
99
     * @return VerdictList
100
     */
101
    public function validate($data): VerdictList
102
    {
103
        return $this->validator->validate($data);
104
    }
105
}
106