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