Passed
Pull Request — master (#99)
by Def
02:50
created

ValidatorFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 42
ccs 18
cts 18
cp 1
rs 10
c 1
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeRules() 0 9 3
A __construct() 0 4 1
A normalizeRule() 0 13 3
A create() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Translator\TranslatorInterface;
8
use Yiisoft\Validator\Rule\Callback;
9
10
final class ValidatorFactory implements ValidatorFactoryInterface
11
{
12
    private ?TranslatorInterface $translator;
13
14 3
    public function __construct(
15
        TranslatorInterface $translator = null
16
    ) {
17 3
        $this->translator = $translator;
18 3
    }
19
20 3
    public function create(array $rules): ValidatorInterface
21
    {
22 3
        return new Validator($this->normalizeRules($rules));
23
    }
24
25 3
    private function normalizeRules(array $rules)
26
    {
27 3
        foreach ($rules as $attribute => $ruleSets) {
28 3
            foreach ($ruleSets as $index => $rule) {
29 3
                $ruleSets[$index] = $this->normalizeRule($rule);
30
            }
31 2
            $rules[$attribute] = $ruleSets;
32
        }
33 2
        return $rules;
34
    }
35
36
    /**
37
     * @param callable|Rule $rule
38
     */
39 3
    private function normalizeRule($rule): Rule
40
    {
41 3
        if (is_callable($rule)) {
42 2
            $rule = new Callback($rule);
0 ignored issues
show
Bug introduced by
It seems like $rule can also be of type Yiisoft\Validator\Rule; however, parameter $callback of Yiisoft\Validator\Rule\Callback::__construct() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

42
            $rule = new Callback(/** @scrutinizer ignore-type */ $rule);
Loading history...
43
        }
44
45 3
        if (!$rule instanceof Rule) {
46 1
            throw new \InvalidArgumentException(
47 1
                'Rule should be either instance of Rule class or a callable'
48
            );
49
        }
50
51 2
        return $rule;
52
    }
53
}
54