|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\I18n\TranslatorInterface; |
|
8
|
|
|
use Yiisoft\Validator\Rule\Callback; |
|
9
|
|
|
|
|
10
|
|
|
final class ValidatorFactory implements ValidatorFactoryInterface |
|
11
|
|
|
{ |
|
12
|
|
|
private ?TranslatorInterface $translator; |
|
13
|
|
|
private ?string $translationDomain; |
|
14
|
|
|
private ?string $translationLocale; |
|
15
|
|
|
|
|
16
|
3 |
|
public function __construct( |
|
17
|
|
|
TranslatorInterface $translator = null, |
|
18
|
|
|
string $translationDomain = null, |
|
19
|
|
|
string $translationLocale = null |
|
20
|
|
|
) { |
|
21
|
3 |
|
$this->translator = $translator; |
|
22
|
3 |
|
$this->translationDomain = $translationDomain; |
|
23
|
3 |
|
$this->translationLocale = $translationLocale; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
3 |
|
public function create(array $rules): ValidatorInterface |
|
27
|
|
|
{ |
|
28
|
3 |
|
return new Validator($this->normalizeRules($rules)); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
3 |
|
private function normalizeRules(array $rules) |
|
32
|
|
|
{ |
|
33
|
3 |
|
foreach ($rules as $attribute => $ruleSets) { |
|
34
|
3 |
|
foreach ($ruleSets as $index => $rule) { |
|
35
|
3 |
|
$ruleSets[$index] = $this->normalizeRule($rule); |
|
36
|
|
|
} |
|
37
|
2 |
|
$rules[$attribute] = $ruleSets; |
|
38
|
|
|
} |
|
39
|
2 |
|
return $rules; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param Rule|callable |
|
44
|
|
|
*/ |
|
45
|
3 |
|
private function normalizeRule($rule): Rule |
|
46
|
|
|
{ |
|
47
|
3 |
|
if (is_callable($rule)) { |
|
48
|
2 |
|
$rule = new Callback($rule); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
3 |
|
if (!$rule instanceof Rule) { |
|
52
|
1 |
|
throw new \InvalidArgumentException( |
|
53
|
1 |
|
'Rule should be either instance of Rule class or a callable' |
|
54
|
|
|
); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
2 |
|
if ($this->translator !== null) { |
|
58
|
1 |
|
$rule = $rule->translator($this->translator); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
2 |
|
if ($this->translationDomain !== null) { |
|
62
|
|
|
$rule = $rule->translationDomain($this->translationDomain); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
if ($this->translationLocale !== null) { |
|
66
|
|
|
$rule = $rule->translationLocale($this->translationLocale); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
2 |
|
return $rule; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|