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
|
2 |
|
public function __construct(string $name, Validator $validator) |
34
|
|
|
{ |
35
|
2 |
|
$this->name = $name; |
36
|
2 |
|
$this->validator = $validator; |
37
|
2 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @return string |
41
|
|
|
*/ |
42
|
2 |
|
public function getName(): string |
43
|
|
|
{ |
44
|
2 |
|
return $this->name; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string|Rule $rule |
49
|
|
|
* @param array $options |
50
|
|
|
* |
51
|
|
|
* @return Rule |
52
|
|
|
*/ |
53
|
2 |
|
public function addRule($rule, array $options = []): Rule |
54
|
|
|
{ |
55
|
2 |
|
if ($rule instanceof Rule) { |
56
|
|
|
$rule->setValidatorAndField($this->validator, $this); |
57
|
|
|
return $this->rules[] = $rule; |
58
|
|
|
} |
59
|
|
|
|
60
|
2 |
|
if (!is_string($rule) || !class_exists($rule) || !is_subclass_of($rule, Rule::class)) { |
61
|
|
|
throw new InvalidArgumentException(sprintf( |
62
|
|
|
'First argument must be an instance of %s or fully qualified name of this class, %s given.', |
63
|
|
|
Rule::class, |
64
|
|
|
is_scalar($rule) ? gettype($rule) : get_class($rule) |
65
|
|
|
)); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** @var Rule $rule */ |
69
|
2 |
|
$rule = new $rule($options); |
70
|
2 |
|
$rule->setValidatorAndField($this->validator, $this); |
71
|
|
|
|
72
|
2 |
|
return $this->rules[] = $rule; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @return Rule[] |
77
|
|
|
*/ |
78
|
2 |
|
public function getRules(): array |
79
|
|
|
{ |
80
|
2 |
|
return $this->rules; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
// |
84
|
|
|
// Methods taken from ValidatorBuilder for easy methods chaining. |
85
|
|
|
// |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @param string $name |
89
|
|
|
* |
90
|
|
|
* @return Field |
91
|
|
|
*/ |
92
|
2 |
|
public function addField(string $name): Field |
93
|
|
|
{ |
94
|
2 |
|
return $this->validator->addField($name); |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
/** |
98
|
|
|
* @param $data |
99
|
|
|
* |
100
|
|
|
* @return VerdictList |
101
|
|
|
*/ |
102
|
|
|
public function validate($data): VerdictList |
103
|
|
|
{ |
104
|
|
|
return $this->validator->validate($data); |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|