-
Notifications
You must be signed in to change notification settings - Fork 11
/
EnumConverter.php
105 lines (90 loc) · 2.45 KB
/
EnumConverter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace mdm\converter;
use \ReflectionClass;
use yii\helpers\Inflector;
/**
* EnumConverter
* Get constant name instead of constant value.
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class EnumConverter extends BaseConverter
{
/**
* @var array
*/
public $enum = [];
/**
* @var string
*/
public $enumPrefix = '';
/**
* @var boolean
*/
public $toWord = true;
/**
* @var array
*/
private static $_constants = [];
/**
* @inheritdoc
*/
protected function convertToLogical($value, $attribute)
{
if ($this->isEmpty($value)) {
return null;
}
if (isset($this->enum[$value])) {
return $this->enum[$value];
}
$names = static::names($this->owner, $this->enumPrefix);
$str = isset($names[$value]) ? $names[$value] : '';
return $this->toWord ? Inflector::camel2words(strtolower($str)) : $str;
}
/**
* @inheritdoc
*/
protected function convertToPhysical($name, $attribute)
{
foreach ($this->enum as $value => $const) {
if ($const == $name) {
return $value;
}
}
$values = static::values($this->owner, $this->enumPrefix);
return isset($values[strtoupper($name)]) ? $values[strtoupper($name)] : null;
}
/**
* Get all constant value
* @param string $className
* @param string $prefix
* @return array
*/
public static function values($className, $prefix = '')
{
if (is_object($className)) {
$className = get_class($className);
}
if (!isset(self::$_constants[$className][$prefix])) {
$ref = new ReflectionClass($className);
self::$_constants[$className][$prefix] = [];
foreach ($ref->getConstants() as $constName => $constValue) {
if ($prefix === '' || strpos($constName, $prefix) === 0) {
self::$_constants[$className][$prefix][substr($constName, strlen($prefix))] = $constValue;
}
}
}
return self::$_constants[$className][$prefix];
}
/**
* Get all constant name
* @param string $className
* @param string $prefix
* @return array
*/
public static function names($className, $prefix = '')
{
return array_flip(static::values($className, $prefix));
}
}