|
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 AttributeValidatorFactory |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var array |
|
15
|
|
|
*/ |
|
16
|
|
|
protected $aliases = [ |
|
17
|
|
|
|
|
18
|
|
|
]; |
|
19
|
|
|
|
|
20
|
|
|
function __construct($aliases = null) |
|
|
|
|
|
|
21
|
|
|
{ |
|
22
|
|
|
if (is_array($aliases)) { |
|
23
|
|
|
$this->aliases = $aliases; |
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param Field $field |
|
29
|
|
|
* @return AttributeValidator |
|
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 AttributeValidator |
|
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
|
|
|
$validator = Yii::createObject($params); |
|
73
|
|
|
|
|
74
|
|
|
return new AttributeValidator($validator); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.