Passed
Push — master ( 2649cb...eabf67 )
by Alexander
01:30
created

ValidatorFactory::normalizeRules()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 9
rs 10
eloc 5
nc 3
nop 1
ccs 6
cts 6
cp 1
crap 3
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