Passed
Pull Request — master (#106)
by Dmitriy
01:57
created

ValidatorFactory::normalizeRule()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
nc 6
nop 1
dl 0
loc 17
ccs 9
cts 9
cp 1
crap 4
rs 10
c 1
b 0
f 0
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|Rule $rule
37
     */
38 3
    private function normalizeRule($rule): Rule
39
    {
40 3
        if (is_callable($rule)) {
41 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

41
            $rule = new Callback(/** @scrutinizer ignore-type */ $rule);
Loading history...
42
        }
43
44 3
        if (!$rule instanceof Rule) {
45 1
            throw new \InvalidArgumentException(
46 1
                'Rule should be either instance of Rule class or a callable'
47
            );
48
        }
49
50 2
        if ($this->formatter !== null) {
51 1
            $rule = $rule->formatter($this->formatter);
52
        }
53
54 2
        return $rule;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $rule could return the type callable which is incompatible with the type-hinted return Yiisoft\Validator\Rule. Consider adding an additional type-check to rule them out.
Loading history...
55
    }
56
}
57