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
|
|
|
} |