1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Runalyze Age Grade. |
5
|
|
|
* |
6
|
|
|
* (c) RUNALYZE <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the MIT license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Runalyze\Common\Enum; |
13
|
|
|
|
14
|
|
|
trait AbstractEnumFactoryTrait |
15
|
|
|
{ |
16
|
|
|
/** @var array|null */ |
17
|
|
|
private static $ClassNames = null; |
18
|
|
|
|
19
|
|
|
/** @var string */ |
20
|
|
|
private static $Namespace = ''; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Get object. |
24
|
|
|
* @param int|string $enum from internal enum |
25
|
|
|
* @return object |
26
|
|
|
* |
27
|
|
|
* @throws \InvalidArgumentException |
28
|
|
|
*/ |
29
|
4 |
|
public static function get($enum) |
30
|
|
|
{ |
31
|
4 |
|
if (null === self::$ClassNames) { |
32
|
2 |
|
self::generateNamespace(); |
33
|
2 |
|
self::generateClassNamesArray(); |
34
|
1 |
|
} |
35
|
|
|
|
36
|
3 |
|
if (!isset(self::$ClassNames[$enum])) { |
37
|
1 |
|
throw new \InvalidArgumentException('Invalid enum "'.$enum.'".'); |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
$className = self::$Namespace.'\\'.self::$ClassNames[$enum]; |
41
|
|
|
|
42
|
2 |
|
return new $className(); |
43
|
|
|
} |
44
|
|
|
|
45
|
2 |
|
private static function generateNamespace() |
46
|
|
|
{ |
47
|
2 |
|
self::$Namespace = substr(get_called_class(), 0, strrpos(get_called_class(), '\\')); |
48
|
2 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @throws \Exception |
52
|
|
|
*/ |
53
|
2 |
|
private static function generateClassNamesArray() |
54
|
|
|
{ |
55
|
2 |
|
if (!method_exists(get_called_class(), 'getEnum')) { |
56
|
1 |
|
throw new \BadMethodCallException('Classes using this trait must have static method getEnum().'); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
self::$ClassNames = array_map(function ($v) { |
60
|
1 |
|
return str_replace(' ', '', ucwords(strtolower(str_replace('_', ' ', $v)))); |
61
|
1 |
|
}, array_flip(self::getEnum())); |
62
|
1 |
|
} |
63
|
|
|
} |
64
|
|
|
|