|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace Warengo\Enum; |
| 4 | + |
| 5 | +use Warengo\Enum\Exceptions\InvalidArgumentException; |
| 6 | +use Warengo\Enum\Storage\EnumStorage; |
| 7 | + |
| 8 | +/** |
| 9 | + * @internal |
| 10 | + */ |
| 11 | +abstract class EnumStatic |
| 12 | +{ |
| 13 | + |
| 14 | + /** @var EnumStorage[] */ |
| 15 | + private static array $storages = []; |
| 16 | + |
| 17 | + /** @var mixed[] */ |
| 18 | + private static array $lists = []; |
| 19 | + |
| 20 | + /** |
| 21 | + * @return string[] |
| 22 | + */ |
| 23 | + abstract protected static function getEnums(): array; |
| 24 | + |
| 25 | + /** |
| 26 | + * @param mixed[] $arguments |
| 27 | + */ |
| 28 | + final public static function __callStatic(string $name, array $arguments) |
| 29 | + { |
| 30 | + if ($name !== strtoupper($name)) { |
| 31 | + throw new InvalidArgumentException(sprintf('Called static class must be uppercase, %s given', $name)); |
| 32 | + } |
| 33 | + |
| 34 | + return static::get($name); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @return static |
| 39 | + */ |
| 40 | + final public static function get(string $name) |
| 41 | + { |
| 42 | + $name = strtolower($name); |
| 43 | + $storage = self::getStorage(); |
| 44 | + if (!$storage->has($name)) { |
| 45 | + if (!isset(self::getEnumsCached()[$name])) { |
| 46 | + throw new InvalidArgumentException( |
| 47 | + sprintf('Enum %s not exists in %s', strtoupper($name), static::class) |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + $storage->set($name, new static($name)); |
| 52 | + } |
| 53 | + |
| 54 | + return $storage->get($name); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @return string[] |
| 59 | + */ |
| 60 | + private static function getEnumsCached(): array |
| 61 | + { |
| 62 | + if (!isset(self::$lists[static::class])) { |
| 63 | + foreach (static::getEnums() as $value) { |
| 64 | + self::$lists[static::class][$value] = true; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return self::$lists[static::class]; |
| 69 | + } |
| 70 | + |
| 71 | + private static function getStorage(): EnumStorage |
| 72 | + { |
| 73 | + if (!isset(self::$storages[static::class])) { |
| 74 | + self::$storages[static::class] = new EnumStorage(static::class); |
| 75 | + } |
| 76 | + |
| 77 | + return self::$storages[static::class]; |
| 78 | + } |
| 79 | + |
| 80 | +} |
0 commit comments