1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the FreshDoctrineEnumBundle |
4
|
|
|
* |
5
|
|
|
* (c) Artem Genvald <[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\DBAL\Types\AbstractEnumType; |
16
|
|
|
use Fresh\DoctrineEnumBundle\Exception\EnumType\EnumTypeIsNotRegisteredException; |
17
|
|
|
use Fresh\DoctrineEnumBundle\Exception\EnumType\NoRegisteredEnumTypesException; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* AbstractEnumExtension. |
21
|
|
|
* |
22
|
|
|
* @author Artem Genvald <[email protected]> |
23
|
|
|
*/ |
24
|
|
|
abstract class AbstractEnumExtension extends \Twig_Extension |
25
|
|
|
{ |
26
|
|
|
/** @var AbstractEnumType[] */ |
27
|
|
|
protected $registeredEnumTypes = []; |
28
|
|
|
|
29
|
|
|
/** @var array */ |
30
|
|
|
protected $occurrences = []; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $registeredTypes |
34
|
|
|
*/ |
35
|
|
|
public function __construct(array $registeredTypes) |
36
|
|
|
{ |
37
|
|
|
foreach ($registeredTypes as $type => $details) { |
38
|
|
|
if (\is_subclass_of($details['class'], AbstractEnumType::class)) { |
|
|
|
|
39
|
|
|
$this->registeredEnumTypes[$type] = $details['class']; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
|
|
protected function hasRegisteredEnumTypes(): bool |
48
|
|
|
{ |
49
|
|
|
return !empty($this->registeredEnumTypes) && \is_array($this->registeredEnumTypes); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @return bool |
54
|
|
|
*/ |
55
|
|
|
protected function onlyOneOccurrenceFound(): bool |
56
|
|
|
{ |
57
|
|
|
return 1 === \count($this->occurrences); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @return bool |
62
|
|
|
*/ |
63
|
|
|
protected function moreThanOneOccurrenceFound(): bool |
64
|
|
|
{ |
65
|
|
|
return 1 < \count($this->occurrences); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @return NoRegisteredEnumTypesException |
70
|
|
|
*/ |
71
|
|
|
protected function createNoRegisteredEnumTypesException(): NoRegisteredEnumTypesException |
72
|
|
|
{ |
73
|
|
|
return new NoRegisteredEnumTypesException('There are no registered ENUM types.'); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param string $enumType |
78
|
|
|
* |
79
|
|
|
* @throws EnumTypeIsNotRegisteredException |
80
|
|
|
*/ |
81
|
|
|
protected function throwExceptionIfEnumTypeIsNotRegistered(string $enumType): void |
82
|
|
|
{ |
83
|
|
|
if (!isset($this->registeredEnumTypes[$enumType])) { |
84
|
|
|
throw new EnumTypeIsNotRegisteredException(\sprintf('ENUM type "%s" is not registered.', $enumType)); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|