Completed
Push — master ( 85994b...9d10cb )
by Dmitry
02:11
created

FieldValidatorFactory::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 0
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 6
1
<?php
2
3
namespace hiapi\validators;
4
5
use hiapi\query\Field;
6
use Yii;
7
use yii\base\InvalidConfigException;
8
use yii\validators\InlineValidator;
9
use yii\validators\Validator;
10
11
class FieldValidatorFactory
12
{
13
    /**
14
     * @var array
15
     */
16
    protected $aliases = [
17
18
    ];
19
20
    function __construct($aliases = null)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
21
    {
22
        if (is_array($aliases)) {
23
            $this->aliases = $aliases;
24
        }
25
    }
26
27
    /**
28
     * @param Field $field
29
     * @return Validator
30
     */
31
    public function createFor(Field $field, $operator)
32
    {
33
        $rule = $field->getAttribute()->getRuleForOperator($operator);
34
35
        return $this->createByDefinition($rule);
36
    }
37
38
    public function createByDefinition($definition)
39
    {
40
        if (is_string($definition)) {
41
            return $this->createByType($definition);
42
        }
43
44
        return $this->createByType($definition[0], array_slice($definition, 1));
45
    }
46
47
    /**
48
     * @param string $type
49
     * @param array $params
50
     * @return Validator
51
     */
52
    public function createByType($type, $params = [])
53
    {
54
        if ($type instanceof \Closure) {
55
            // method-based validator
56
            $params['class'] = InlineValidator::class;
57
            $params['method'] = $type;
58
        } else {
59
            if (isset(Validator::$builtInValidators[$type])) {
60
                $type = Validator::$builtInValidators[$type];
61
            } elseif (isset($this->aliases[$type])) {
62
                $type = $this->aliases[$type];
63
            }
64
65
            if (is_array($type)) {
66
                $params = array_merge($type, $params);
67
            } else {
68
                $params['class'] = $type;
69
            }
70
        }
71
72
        return Yii::createObject($params);
73
    }
74
}
75