1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Yiisoft\Validator; |
||
6 | |||
7 | use Yiisoft\Validator\Rule\Callback; |
||
8 | |||
9 | final class ValidatorFactory implements ValidatorFactoryInterface |
||
10 | { |
||
11 | private ?FormatterInterface $formatter; |
||
12 | |||
13 | 3 | public function __construct( |
|
14 | FormatterInterface $formatter = null |
||
15 | ) { |
||
16 | 3 | $this->formatter = $formatter; |
|
17 | 3 | } |
|
18 | |||
19 | 3 | public function create(array $rules): ValidatorInterface |
|
20 | { |
||
21 | 3 | return new Validator($this->normalizeRules($rules)); |
|
22 | } |
||
23 | |||
24 | 3 | private function normalizeRules(array $rules) |
|
25 | { |
||
26 | 3 | foreach ($rules as $attribute => $ruleSets) { |
|
27 | 3 | foreach ($ruleSets as $index => $rule) { |
|
28 | 3 | $ruleSets[$index] = $this->normalizeRule($rule); |
|
29 | } |
||
30 | 2 | $rules[$attribute] = $ruleSets; |
|
31 | } |
||
32 | 2 | return $rules; |
|
33 | } |
||
34 | |||
35 | /** |
||
36 | * @param callable|RuleInterface $rule |
||
37 | */ |
||
38 | 3 | private function normalizeRule($rule): RuleInterface |
|
39 | { |
||
40 | 3 | if (is_callable($rule)) { |
|
41 | 2 | $rule = new Callback($rule); |
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
42 | } |
||
43 | |||
44 | 3 | if (!$rule instanceof RuleInterface) { |
|
45 | 1 | throw new \InvalidArgumentException(sprintf( |
|
46 | 1 | 'Rule should be either instance of %s or a callable', |
|
47 | 1 | RuleInterface::class |
|
48 | )); |
||
49 | } |
||
50 | |||
51 | 2 | if ($this->formatter !== null && $rule instanceof FormattableRuleInterface) { |
|
52 | 1 | $rule = $rule->formatter($this->formatter); |
|
53 | } |
||
54 | |||
55 | 2 | return $rule; |
|
56 | } |
||
57 | } |
||
58 |