1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the "elao/enum" package. |
5
|
|
|
* |
6
|
|
|
* Copyright (C) Elao |
7
|
|
|
* |
8
|
|
|
* @author Elao <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Elao\Enum\Bridge\Twig\Extension; |
12
|
|
|
|
13
|
|
|
use Elao\Enum\EnumInterface; |
14
|
|
|
use Twig\Extension\AbstractExtension; |
15
|
|
|
use Twig\TwigFunction; |
16
|
|
|
|
17
|
|
|
class EnumExtension extends AbstractExtension |
18
|
|
|
{ |
19
|
|
|
public function getFunctions() |
20
|
|
|
{ |
21
|
|
|
return [ |
22
|
|
|
new TwigFunction('enum_get', [$this, 'get']), |
23
|
|
|
new TwigFunction('enum_values', [$this, 'values']), |
24
|
|
|
new TwigFunction('enum_accepts', [$this, 'accepts']), |
25
|
|
|
new TwigFunction('enum_instances', [$this, 'instances']), |
26
|
|
|
]; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function get(string $className, $value): EnumInterface |
30
|
|
|
{ |
31
|
|
|
$this->esureEnum($className); |
32
|
|
|
|
33
|
|
|
return \call_user_func([$className, 'get'], $value); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function values(string $className): array |
37
|
|
|
{ |
38
|
|
|
$this->esureEnum($className); |
39
|
|
|
|
40
|
|
|
return \call_user_func([$className, 'values']); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function accepts(string $className, $value): bool |
44
|
|
|
{ |
45
|
|
|
$this->esureEnum($className); |
46
|
|
|
|
47
|
|
|
return \call_user_func([$className, 'accepts'], $value); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function instances(string $className): array |
51
|
|
|
{ |
52
|
|
|
$this->esureEnum($className); |
53
|
|
|
|
54
|
|
|
return \call_user_func([$className, 'instances']); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function esureEnum(string $className) |
58
|
|
|
{ |
59
|
|
|
if (!is_a($className, EnumInterface::class)) { |
60
|
|
|
throw new Exception("$className is not an Enum."); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|