Passed
Push — master ( 144685...73f4bb )
by Alexander
01:42
created

ConstRangeValidator::getClosure()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 18
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 1
nop 0
crap 20
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: horat1us
5
 * Date: 7/31/17
6
 * Time: 4:02 PM
7
 */
8
9
namespace Horat1us\Yii\Validators;
10
11
use yii\validators\RangeValidator;
12
13
14
/**
15
 * Class ConstRangeValidator
16
 * @package common\validators
17
 */
18
class ConstRangeValidator extends RangeValidator
19
{
20
    /**
21
     * Prefix for constants (default $attribute) will be used
22
     *
23
     * @var
24
     */
25
    public $prefix;
26
27
    /**
28
     * @var bool
29
     */
30
    public $strict = true;
31
32
    /**
33
     * @var string Class with const range (model class will be used by default)
34
     */
35
    public $targetClass;
36
37
    /**
38
     * @var callable
39
     */
40
    public $filter;
41
42
    public static $ranges = [];
43
44
    /**
45
     * @return void
46
     */
47
    public function init()
48
    {
49
        $this->range = $this->getClosure();
50
        parent::init();
51
    }
52
53
    /**
54
     * @return \Closure
55
     */
56
    public function getClosure(): \Closure
57
    {
58
        return function ($model, $attribute) {
59
            $prefix = $this->prefix ?? strtoupper($attribute) . '_';
60
            $class = $this->targetClass ?? get_class($model);
61
62
            $cache = ConstRangeValidator::$ranges[$class][$prefix] ?? null;
63
            if ($cache instanceof \Traversable) {
64
                return $cache;
65
            }
66
67
            $reflection = new \ReflectionClass($class);
68
            $cache[$class][$prefix] = [];
69
            foreach ($reflection->getConstants() as $name => $v) {
70
                if (strpos($name, $prefix) === 0) {
71
                    $cache[$class][$prefix][] = $v;
72
                }
73
            }
74
        };
75
    }
76
77
    /**
78
     * @param mixed $value
79
     * @return array|null
80
     */
81
    protected function validateValue($value)
82
    {
83
        if (is_callable($this->filter)) {
84
            $value = call_user_func($this->filter, $value);
85
        }
86
        return parent::validateValue($value);
87
    }
88
89
    /**
90
     * @inheritdoc
91
     */
92
    public function validateAttribute($model, $attribute)
93
    {
94
        parent::validateAttribute($model, $attribute);
95
        $this->range = $this->getClosure();
96
    }
97
}