1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Validator validates {@link DataSetInterface} against rules set for data set attributes. |
9
|
|
|
*/ |
10
|
|
|
final class Validator implements ValidatorInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var Rules[] |
14
|
|
|
*/ |
15
|
|
|
private array $attributeRules = []; |
16
|
|
|
|
17
|
7 |
|
public function __construct(iterable $rules = []) |
18
|
|
|
{ |
19
|
7 |
|
foreach ($rules as $attribute => $ruleSets) { |
20
|
6 |
|
if ($ruleSets instanceof Rule) { |
21
|
2 |
|
$ruleSets = [$ruleSets]; |
22
|
6 |
|
} elseif (!is_iterable($ruleSets)) { |
23
|
1 |
|
throw new \InvalidArgumentException('Attribute rules should be either an instance of Rule class or an array of instances of Rule class.'); |
24
|
|
|
} |
25
|
5 |
|
foreach ($ruleSets as $rule) { |
26
|
5 |
|
$this->addRule($attribute, $rule); |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
4 |
|
public function validate(DataSetInterface $dataSet): ResultSet |
32
|
|
|
{ |
33
|
4 |
|
$results = new ResultSet(); |
34
|
4 |
|
foreach ($this->attributeRules as $attribute => $rules) { |
35
|
4 |
|
$results->addResult( |
36
|
4 |
|
$attribute, |
37
|
4 |
|
$rules->validate($dataSet->getAttributeValue($attribute), $dataSet) |
38
|
|
|
); |
39
|
|
|
} |
40
|
4 |
|
return $results; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $attribute |
45
|
|
|
* @param Rule|callable |
46
|
|
|
*/ |
47
|
6 |
|
public function addRule(string $attribute, $rule): void |
48
|
|
|
{ |
49
|
6 |
|
if (!isset($this->attributeRules[$attribute])) { |
50
|
6 |
|
$this->attributeRules[$attribute] = new Rules([]); |
51
|
|
|
} |
52
|
6 |
|
$this->attributeRules[$attribute]->add($rule); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Return all attribute rules as array. |
57
|
|
|
* |
58
|
|
|
* For example: |
59
|
|
|
* |
60
|
|
|
* ```php |
61
|
|
|
* [ |
62
|
|
|
* 'amount' => [ |
63
|
|
|
* [ |
64
|
|
|
* 'number', |
65
|
|
|
* 'integer' => true, |
66
|
|
|
* 'max' => 100, |
67
|
|
|
* 'notANumberMessage' => 'Value must be an integer.', |
68
|
|
|
* 'tooBigMessage' => 'Value must be no greater than 100.' |
69
|
|
|
* ], |
70
|
|
|
* ['callback'], |
71
|
|
|
* ], |
72
|
|
|
* 'name' => [ |
73
|
|
|
* 'hasLength', |
74
|
|
|
* 'max' => 20, |
75
|
|
|
* 'message' => 'Value must contain at most 20 characters.' |
76
|
|
|
* ], |
77
|
|
|
* ] |
78
|
|
|
* ``` |
79
|
|
|
* |
80
|
|
|
* @return array |
81
|
|
|
*/ |
82
|
2 |
|
public function asArray(): array |
83
|
|
|
{ |
84
|
2 |
|
$rulesOfArray = []; |
85
|
2 |
|
foreach ($this->attributeRules as $attribute => $rules) { |
86
|
2 |
|
$rulesOfArray[$attribute] = $rules->asArray(); |
87
|
|
|
} |
88
|
2 |
|
return $rulesOfArray; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|