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

Field::addRule()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 9.1595

Importance

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