Skip to content

Instantly share code, notes, and snippets.

@wbarcovsky
Last active June 18, 2018 08:20
Show Gist options
  • Select an option

  • Save wbarcovsky/96c2a8cbd1ca0668b7491de54dca213f to your computer and use it in GitHub Desktop.

Select an option

Save wbarcovsky/96c2a8cbd1ca0668b7491de54dca213f to your computer and use it in GitHub Desktop.
<?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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment