Completed
Push — master ( be2280...4a4169 )
by Andrii
01:43
created

AttributeValidatorFactory::createByDefinition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * HiAPI Yii2 base project for building API
4
 *
5
 * @link      https://github.com/hiqdev/hiapi
6
 * @package   hiapi
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiapi\validators;
12
13
use Yii;
14
use yii\validators\InlineValidator;
15
use yii\validators\Validator;
16
17
class AttributeValidatorFactory
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $aliases = [
23
    ];
24
25
    public function __construct($aliases = null)
26
    {
27
        if (is_array($aliases)) {
28
            $this->aliases = $aliases;
29
        }
30
    }
31
32
    public function createByDefinition($definition)
33
    {
34
        if (is_string($definition)) {
35
            return $this->createByType($definition);
36
        }
37
38
        return $this->createByType($definition[0], array_slice($definition, 1));
39
    }
40
41
    /**
42
     * @param string $type
43
     * @param array $params
44
     * @return AttributeValidator
45
     */
46
    public function createByType($type, $params = [])
47
    {
48
        if ($type instanceof \Closure) {
49
            // method-based validator
50
            $params['class'] = InlineValidator::class;
51
            $params['method'] = $type;
52
        } else {
53
            if (isset(Validator::$builtInValidators[$type])) {
54
                $type = Validator::$builtInValidators[$type];
55
            } elseif (isset($this->aliases[$type])) {
56
                $type = $this->aliases[$type];
57
            }
58
59
            if (is_array($type)) {
60
                $params = array_merge($type, $params);
61
            } else {
62
                $params['class'] = $type;
63
            }
64
        }
65
66
        $validator = Yii::createObject($params);
67
68
        return new AttributeValidator($validator);
69
    }
70
}
71