1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\Rule\Callback; |
8
|
|
|
use Yiisoft\I18n\TranslatorInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Validator validates {@link DataSetInterface} against rules set for data set attributes. |
12
|
|
|
*/ |
13
|
|
|
class Validator implements ValidatorInterface |
14
|
|
|
{ |
15
|
|
|
private ?TranslatorInterface $translator; |
16
|
|
|
private ?string $translationDomain; |
17
|
|
|
private ?string $translationLocale; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Rules[] |
21
|
|
|
*/ |
22
|
|
|
private array $attributeRules = []; |
23
|
|
|
|
24
|
2 |
|
public function __construct( |
25
|
|
|
TranslatorInterface $translator = null, |
26
|
|
|
string $translationDomain = null, |
27
|
|
|
string $translationLocale = null |
28
|
|
|
) { |
29
|
|
|
$this->translator = $translator; |
30
|
2 |
|
$this->translationDomain = $translationDomain; |
31
|
2 |
|
$this->translationLocale = $translationLocale; |
32
|
2 |
|
} |
33
|
|
|
|
34
|
2 |
|
public function validate(DataSetInterface $dataSet): ResultSet |
35
|
1 |
|
{ |
36
|
1 |
|
$results = new ResultSet(); |
37
|
1 |
|
foreach ($this->attributeRules as $attribute => $rules) { |
38
|
|
|
$results->addResult( |
39
|
1 |
|
$attribute, |
40
|
|
|
$rules->validate($dataSet->getAttributeValue($attribute), $dataSet) |
41
|
|
|
); |
42
|
|
|
} |
43
|
|
|
return $results; |
44
|
2 |
|
} |
45
|
|
|
|
46
|
2 |
|
public function addRule(string $attribute, Rule $rule): void |
47
|
2 |
|
{ |
48
|
2 |
|
if (!isset($this->attributeRules[$attribute])) { |
49
|
2 |
|
$this->attributeRules[$attribute] = new Rules( |
50
|
2 |
|
[], |
51
|
|
|
$this->translator, |
52
|
|
|
$this->translationDomain, |
53
|
2 |
|
$this->translationLocale |
54
|
|
|
); |
55
|
|
|
} |
56
|
2 |
|
|
57
|
|
|
$this->attributeRules[$attribute]->add($rule); |
58
|
2 |
|
} |
59
|
2 |
|
|
60
|
2 |
|
public function addRules(iterable $rules = []): void |
61
|
2 |
|
{ |
62
|
2 |
|
foreach ($rules as $attribute => $ruleSets) { |
63
|
2 |
|
foreach ($ruleSets as $rule) { |
64
|
|
|
if (is_callable($rule)) { |
65
|
|
|
$rule = new Callback($rule); |
66
|
|
|
} |
67
|
2 |
|
$this->addRule($attribute, $rule); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|