Passed
Pull Request — master (#99)
by Def
02:50
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\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