Passed
Push — master ( 73f4bb...01b75b )
by Alexander
01:38
created

ConstRangeValidator::getClosure()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
ccs 0
cts 19
cp 0
rs 8.7972
cc 4
eloc 13
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
70
            foreach ($reflection->getConstants() as $name => $v) {
71
                if (strpos($name, $prefix) === 0) {
72
                    $cache[$class][$prefix][] = $v;
73
                }
74
            }
75
76
            return $cache[$class][$prefix];
77
        };
78
    }
79
80
    /**
81
     * @param mixed $value
82
     * @return array|null
83
     */
84
    protected function validateValue($value)
85
    {
86
        if (is_callable($this->filter)) {
87
            $value = call_user_func($this->filter, $value);
88
        }
89
        return parent::validateValue($value);
90
    }
91
92
    /**
93
     * @inheritdoc
94
     */
95
    public function validateAttribute($model, $attribute)
96
    {
97
        parent::validateAttribute($model, $attribute);
98
        $this->range = $this->getClosure();
99
    }
100
}