1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ElfSundae\Laravel\Support; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Arr; |
6
|
|
|
use MyCLabs\Enum\Enum as PhpEnum; |
7
|
|
|
use ElfSundae\Laravel\Support\Traits\EnumDefaultKey; |
8
|
|
|
use ElfSundae\Laravel\Support\Traits\EnumTransferKeys; |
9
|
|
|
|
10
|
|
|
abstract class Enum extends PhpEnum |
11
|
|
|
{ |
12
|
|
|
use EnumTransferKeys, EnumDefaultKey; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Get the key for the given value. |
16
|
|
|
* |
17
|
|
|
* @param mixed $value |
18
|
|
|
* @return mixed |
19
|
|
|
*/ |
20
|
|
|
public static function key($value) |
21
|
|
|
{ |
22
|
|
|
return static::search($value); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Get the value for the given key. |
27
|
|
|
* |
28
|
|
|
* @param mixed $key |
29
|
|
|
* @return mixed |
30
|
|
|
*/ |
31
|
|
|
public static function value($key) |
32
|
|
|
{ |
33
|
|
|
return Arr::get( |
34
|
|
|
static::toArray(), |
35
|
|
|
static::getOriginalKey($key), |
36
|
|
|
static::defaultValue() |
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Get all values. |
42
|
|
|
* |
43
|
|
|
* @return array |
44
|
|
|
*/ |
45
|
|
|
public static function allValues() |
46
|
|
|
{ |
47
|
|
|
return array_values(static::toArray()); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Get all keys. |
52
|
|
|
* |
53
|
|
|
* @return array |
54
|
|
|
*/ |
55
|
|
|
public static function allKeys() |
56
|
|
|
{ |
57
|
|
|
return array_map(function ($key) { |
58
|
|
|
return static::getTransferredKey($key); |
59
|
|
|
}, static::keys()); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Get the key for the given value. |
64
|
|
|
* |
65
|
|
|
* @param mixed $value |
66
|
|
|
* @return mixed |
67
|
|
|
*/ |
68
|
|
|
public static function search($value) |
69
|
|
|
{ |
70
|
|
|
$key = parent::search($value); |
71
|
|
|
|
72
|
|
|
if ($key === false) { |
73
|
|
|
$key = static::defaultKey(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return static::getTransferredKey($key); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Check if is valid enum key. |
81
|
|
|
* |
82
|
|
|
* @param mixed $key |
83
|
|
|
* @return bool |
84
|
|
|
*/ |
85
|
|
|
public static function isValidKey($key) |
86
|
|
|
{ |
87
|
|
|
return parent::isValidKey(static::getOriginalKey($key)); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* Returns a value when called statically like so: |
92
|
|
|
* MyEnum::SOME_VALUE() given SOME_VALUE is a class constant |
93
|
|
|
* |
94
|
|
|
* @param string $name |
95
|
|
|
* @param array $arguments |
96
|
|
|
* @return static |
97
|
|
|
*/ |
98
|
|
|
public static function __callStatic($name, $arguments) |
99
|
|
|
{ |
100
|
|
|
return new static(static::value($name)); |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|