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

FieldValidatorFactory   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
c 0
b 0
f 0
lcom 1
cbo 4
dl 0
loc 64
ccs 0
cts 33
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A createFor() 0 6 1
A createByDefinition() 0 8 2
B createByType() 0 22 5
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