1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the FreshDoctrineEnumBundle |
4
|
|
|
* |
5
|
|
|
* (c) Artem Henvald <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
declare(strict_types=1); |
12
|
|
|
|
13
|
|
|
namespace Fresh\DoctrineEnumBundle\Twig\Extension; |
14
|
|
|
|
15
|
|
|
use Fresh\DoctrineEnumBundle\Exception\EnumType\EnumTypeIsNotRegisteredException; |
16
|
|
|
use Fresh\DoctrineEnumBundle\Exception\EnumType\NoRegisteredEnumTypesException; |
17
|
|
|
use Twig\TwigFunction; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* EnumValuesAsArrayTwigExtension. |
21
|
|
|
* |
22
|
|
|
* @author Artem Henvald <[email protected]> |
23
|
|
|
*/ |
24
|
|
|
class EnumValuesAsArrayTwigExtension extends AbstractEnumTwigExtension |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
|
public function getFunctions(): array |
30
|
|
|
{ |
31
|
|
|
return [ |
32
|
|
|
new TwigFunction('enum_values', [$this, 'getEnumValuesAsArray']), |
33
|
|
|
new TwigFunction('enum_readable_values', [$this, 'getReadableEnumValuesAsArray']), |
34
|
|
|
]; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param string $enumType |
39
|
|
|
* |
40
|
|
|
* @throws EnumTypeIsNotRegisteredException |
41
|
|
|
* @throws NoRegisteredEnumTypesException |
42
|
|
|
* |
43
|
|
|
* @return array |
44
|
|
|
*/ |
45
|
|
|
public function getEnumValuesAsArray(string $enumType): array |
46
|
|
|
{ |
47
|
|
|
return $this->callEnumTypeStaticMethod($enumType, 'getValues'); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param string $enumType |
52
|
|
|
* |
53
|
|
|
* @throws EnumTypeIsNotRegisteredException |
54
|
|
|
* @throws NoRegisteredEnumTypesException |
55
|
|
|
* |
56
|
|
|
* @return array |
57
|
|
|
*/ |
58
|
|
|
public function getReadableEnumValuesAsArray(string $enumType): array |
59
|
|
|
{ |
60
|
|
|
return $this->callEnumTypeStaticMethod($enumType, 'getReadableValues'); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string $enumType |
65
|
|
|
* @param string $staticMethodName |
66
|
|
|
* |
67
|
|
|
* @throws EnumTypeIsNotRegisteredException |
68
|
|
|
* @throws NoRegisteredEnumTypesException |
69
|
|
|
* |
70
|
|
|
* @return array |
71
|
|
|
*/ |
72
|
|
|
private function callEnumTypeStaticMethod(string $enumType, string $staticMethodName): array |
73
|
|
|
{ |
74
|
|
|
if ($this->hasRegisteredEnumTypes()) { |
75
|
|
|
$this->throwExceptionIfEnumTypeIsNotRegistered($enumType); |
76
|
|
|
|
77
|
|
|
return \call_user_func([$this->registeredEnumTypes[$enumType], $staticMethodName]); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
throw $this->createNoRegisteredEnumTypesException(); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|