Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Enum
- {
- private static $values = [];
- private static $valueMap = [];
- private $value;
- public function __construct($value)
- {
- $this->value = $value;
- }
- public function getValue()
- {
- return $this->value;
- }
- public function __toString()
- {
- return $this->value;
- }
- /**
- * @return Enum[]
- * @throws \Exception
- */
- public static function getValues()
- {
- $className = get_called_class();
- if (!array_key_exists($className, self::$values)) {
- throw new \Exception(sprintf("Enum is not initialized, enum=%s", $className));
- }
- return self::$values[$className];
- }
- public static function getEnumObject($value)
- {
- if (empty($value)) {
- return null;
- }
- $className = get_called_class();
- return self::$valueMap[$className][$value];
- }
- public static function init()
- {
- $className = get_called_class();
- $class = new \ReflectionClass($className);
- if (array_key_exists($className, self::$values)) {
- throw new \Exception(sprintf("Enum has been already initialized, enum=%s", $className));
- }
- self::$values[$className] = [];
- self::$valueMap[$className] = [];
- /** @var Enum[] $enumFields */
- $enumFields = array_filter($class->getStaticProperties(), function ($property) {
- return $property instanceof Enum;
- });
- if (count($enumFields) == 0) {
- throw new \Exception(sprintf("Enum has not values, enum=%s", $className));
- }
- foreach ($enumFields as $property) {
- if (array_key_exists($property->getValue(), self::$valueMap[$className])) {
- throw new \Exception(sprintf("Duplicate enum value %s from enum %s", $property->getValue(), $className));
- }
- self::$values[$className][] = $property;
- self::$valueMap[$className][$property->getValue()] = $property;
- }
- }
- }
- /**
- * Пример реализации конкретного класса:
- */
- class Format extends Enum
- {
- public static $WEB;
- public static $GOST;
- }
- Format::$WEB = new Format('web');
- Format::$GOST = new Format('gost');
Add Comment
Please, Sign In to add comment