Guest User

Untitled

a guest
Jun 19th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. <?php
  2. class Enum
  3. {
  4. private static $values = [];
  5. private static $valueMap = [];
  6.  
  7. private $value;
  8.  
  9. public function __construct($value)
  10. {
  11. $this->value = $value;
  12. }
  13.  
  14. public function getValue()
  15. {
  16. return $this->value;
  17. }
  18.  
  19. public function __toString()
  20. {
  21. return $this->value;
  22. }
  23.  
  24.  
  25. /**
  26. * @return Enum[]
  27. * @throws \Exception
  28. */
  29. public static function getValues()
  30. {
  31. $className = get_called_class();
  32. if (!array_key_exists($className, self::$values)) {
  33. throw new \Exception(sprintf("Enum is not initialized, enum=%s", $className));
  34. }
  35. return self::$values[$className];
  36. }
  37.  
  38. public static function getEnumObject($value)
  39. {
  40. if (empty($value)) {
  41. return null;
  42. }
  43. $className = get_called_class();
  44. return self::$valueMap[$className][$value];
  45. }
  46.  
  47. public static function init()
  48. {
  49. $className = get_called_class();
  50. $class = new \ReflectionClass($className);
  51.  
  52. if (array_key_exists($className, self::$values)) {
  53. throw new \Exception(sprintf("Enum has been already initialized, enum=%s", $className));
  54. }
  55. self::$values[$className] = [];
  56. self::$valueMap[$className] = [];
  57.  
  58.  
  59. /** @var Enum[] $enumFields */
  60. $enumFields = array_filter($class->getStaticProperties(), function ($property) {
  61. return $property instanceof Enum;
  62. });
  63. if (count($enumFields) == 0) {
  64. throw new \Exception(sprintf("Enum has not values, enum=%s", $className));
  65. }
  66.  
  67. foreach ($enumFields as $property) {
  68. if (array_key_exists($property->getValue(), self::$valueMap[$className])) {
  69. throw new \Exception(sprintf("Duplicate enum value %s from enum %s", $property->getValue(), $className));
  70. }
  71.  
  72. self::$values[$className][] = $property;
  73. self::$valueMap[$className][$property->getValue()] = $property;
  74. }
  75. }
  76. }
  77.  
  78. /**
  79. * Пример реализации конкретного класса:
  80. */
  81. class Format extends Enum
  82. {
  83. public static $WEB;
  84. public static $GOST;
  85. }
  86.  
  87. Format::$WEB = new Format('web');
  88. Format::$GOST = new Format('gost');
Add Comment
Please, Sign In to add comment