Zingle /
PHP-Enum
| 1 | <?php |
||
| 2 | |||
| 3 | namespace ZingleCom\Enum\Meta; |
||
| 4 | |||
| 5 | use phootwork\collection\Map; |
||
| 6 | use ZingleCom\Enum\AbstractEnum; |
||
| 7 | use ZingleCom\Enum\Exception\EnumException; |
||
| 8 | use ZingleCom\Enum\Meta; |
||
| 9 | use ZingleCom\Enum\MetaInterface; |
||
| 10 | |||
| 11 | /** |
||
| 12 | * Class Generator |
||
| 13 | */ |
||
| 14 | class Generator implements GeneratorInterface |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * @var Map |
||
| 18 | */ |
||
| 19 | private $meta; |
||
| 20 | |||
| 21 | |||
| 22 | /** |
||
| 23 | * MetaGenerator constructor. |
||
| 24 | */ |
||
| 25 | public function __construct() |
||
| 26 | { |
||
| 27 | $this->meta = new Map(); |
||
| 28 | } |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @param string|AbstractEnum $enumClass |
||
| 32 | * @return MetaInterface |
||
| 33 | * @throws EnumException |
||
| 34 | */ |
||
| 35 | public function get(string $enumClass): MetaInterface |
||
| 36 | { |
||
| 37 | if (!$this->meta->has($enumClass)) { |
||
| 38 | $this->meta->set($enumClass, $this->create($enumClass)); |
||
| 39 | } |
||
| 40 | |||
| 41 | return $this->meta->get($enumClass); |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 42 | } |
||
| 43 | |||
| 44 | /** |
||
| 45 | * @param string $enumClass |
||
| 46 | * @return MetaInterface |
||
| 47 | * @throws EnumException |
||
| 48 | */ |
||
| 49 | private function create(string $enumClass): MetaInterface |
||
| 50 | { |
||
| 51 | try { |
||
| 52 | $refl = new \ReflectionClass($enumClass); |
||
| 53 | if (!$refl->isSubclassOf(AbstractEnum::class)) { |
||
| 54 | throw new EnumException(sprintf('Enum\'s must be of type %s', AbstractEnum::class)); |
||
| 55 | } |
||
| 56 | |||
| 57 | $constants = []; |
||
| 58 | $reflConstants = $refl->getReflectionConstants(); |
||
| 59 | foreach ($reflConstants as $reflConstant) { |
||
| 60 | // don't add private constants to value value list. |
||
| 61 | if ($reflConstant->isPrivate()) { |
||
| 62 | continue; |
||
| 63 | } |
||
| 64 | |||
| 65 | $constants[$reflConstant->getName()] = $reflConstant->getValue(); |
||
| 66 | } |
||
| 67 | |||
| 68 | return new Meta($constants); |
||
| 69 | } catch (\ReflectionException $e) { |
||
| 70 | throw new EnumException($e->getMessage(), $e->getCode(), $e); |
||
| 71 | } |
||
| 72 | } |
||
| 73 | } |
||
| 74 |