AbstractEnum.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. declare(strict_types = 1);
  3. namespace DASPRiD\Enum;
  4. use DASPRiD\Enum\Exception\CloneNotSupportedException;
  5. use DASPRiD\Enum\Exception\IllegalArgumentException;
  6. use DASPRiD\Enum\Exception\MismatchException;
  7. use DASPRiD\Enum\Exception\SerializeNotSupportedException;
  8. use DASPRiD\Enum\Exception\UnserializeNotSupportedException;
  9. use ReflectionClass;
  10. abstract class AbstractEnum
  11. {
  12. /**
  13. * @var string
  14. */
  15. private $name;
  16. /**
  17. * @var int
  18. */
  19. private $ordinal;
  20. /**
  21. * @var array<string, array<string, static>>
  22. */
  23. private static $values = [];
  24. /**
  25. * @var array<string, bool>
  26. */
  27. private static $allValuesLoaded = [];
  28. /**
  29. * @var array<string, array>
  30. */
  31. private static $constants = [];
  32. /**
  33. * The constructor is private by default to avoid arbitrary enum creation.
  34. *
  35. * When creating your own constructor for a parameterized enum, make sure to declare it as protected, so that
  36. * the static methods are able to construct it. Avoid making it public, as that would allow creation of
  37. * non-singleton enum instances.
  38. */
  39. private function __construct()
  40. {
  41. }
  42. /**
  43. * Magic getter which forwards all calls to {@see self::valueOf()}.
  44. *
  45. * @return static
  46. */
  47. final public static function __callStatic(string $name, array $arguments) : self
  48. {
  49. return static::valueOf($name);
  50. }
  51. /**
  52. * Returns an enum with the specified name.
  53. *
  54. * The name must match exactly an identifier used to declare an enum in this type (extraneous whitespace characters
  55. * are not permitted).
  56. *
  57. * @return static
  58. * @throws IllegalArgumentException if the enum has no constant with the specified name
  59. */
  60. final public static function valueOf(string $name) : self
  61. {
  62. if (isset(self::$values[static::class][$name])) {
  63. return self::$values[static::class][$name];
  64. }
  65. $constants = self::constants();
  66. if (array_key_exists($name, $constants)) {
  67. return self::createValue($name, $constants[$name][0], $constants[$name][1]);
  68. }
  69. throw new IllegalArgumentException(sprintf('No enum constant %s::%s', static::class, $name));
  70. }
  71. /**
  72. * @return static
  73. */
  74. final private static function createValue(string $name, int $ordinal, array $arguments) : self
  75. {
  76. $instance = new static(...$arguments);
  77. $instance->name = $name;
  78. $instance->ordinal = $ordinal;
  79. self::$values[static::class][$name] = $instance;
  80. return $instance;
  81. }
  82. /**
  83. * Obtains all possible types defined by this enum.
  84. *
  85. * @return static[]
  86. */
  87. final public static function values() : array
  88. {
  89. if (isset(self::$allValuesLoaded[static::class])) {
  90. return self::$values[static::class];
  91. }
  92. if (! isset(self::$values[static::class])) {
  93. self::$values[static::class] = [];
  94. }
  95. foreach (self::constants() as $name => $constant) {
  96. if (array_key_exists($name, self::$values[static::class])) {
  97. continue;
  98. }
  99. static::createValue($name, $constant[0], $constant[1]);
  100. }
  101. uasort(self::$values[static::class], function (self $a, self $b) {
  102. return $a->ordinal() <=> $b->ordinal();
  103. });
  104. self::$allValuesLoaded[static::class] = true;
  105. return self::$values[static::class];
  106. }
  107. final private static function constants() : array
  108. {
  109. if (isset(self::$constants[static::class])) {
  110. return self::$constants[static::class];
  111. }
  112. self::$constants[static::class] = [];
  113. $reflectionClass = new ReflectionClass(static::class);
  114. $ordinal = -1;
  115. foreach ($reflectionClass->getReflectionConstants() as $reflectionConstant) {
  116. if (! $reflectionConstant->isProtected()) {
  117. continue;
  118. }
  119. $value = $reflectionConstant->getValue();
  120. self::$constants[static::class][$reflectionConstant->name] = [
  121. ++$ordinal,
  122. is_array($value) ? $value : []
  123. ];
  124. }
  125. return self::$constants[static::class];
  126. }
  127. /**
  128. * Returns the name of this enum constant, exactly as declared in its enum declaration.
  129. *
  130. * Most programmers should use the {@see self::__toString()} method in preference to this one, as the toString
  131. * method may return a more user-friendly name. This method is designed primarily for use in specialized situations
  132. * where correctness depends on getting the exact name, which will not vary from release to release.
  133. */
  134. final public function name() : string
  135. {
  136. return $this->name;
  137. }
  138. /**
  139. * Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial
  140. * constant is assigned an ordinal of zero).
  141. *
  142. * Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data
  143. * structures.
  144. */
  145. final public function ordinal() : int
  146. {
  147. return $this->ordinal;
  148. }
  149. /**
  150. * Compares this enum with the specified object for order.
  151. *
  152. * Returns negative integer, zero or positive integer as this object is less than, equal to or greater than the
  153. * specified object.
  154. *
  155. * Enums are only comparable to other enums of the same type. The natural order implemented by this method is the
  156. * order in which the constants are declared.
  157. *
  158. * @throws MismatchException if the passed enum is not of the same type
  159. */
  160. final public function compareTo(self $other) : int
  161. {
  162. if (! $other instanceof static) {
  163. throw new MismatchException(sprintf(
  164. 'The passed enum %s is not of the same type as %s',
  165. get_class($other),
  166. static::class
  167. ));
  168. }
  169. return $this->ordinal - $other->ordinal;
  170. }
  171. /**
  172. * Forbid cloning enums.
  173. *
  174. * @throws CloneNotSupportedException
  175. */
  176. final public function __clone()
  177. {
  178. throw new CloneNotSupportedException();
  179. }
  180. /**
  181. * Forbid serializing enums.
  182. *
  183. * @throws SerializeNotSupportedException
  184. */
  185. final public function __sleep() : void
  186. {
  187. throw new SerializeNotSupportedException();
  188. }
  189. /**
  190. * Forbid unserializing enums.
  191. *
  192. * @throws UnserializeNotSupportedException
  193. */
  194. final public function __wakeup() : void
  195. {
  196. throw new UnserializeNotSupportedException();
  197. }
  198. /**
  199. * Turns the enum into a string representation.
  200. *
  201. * You may override this method to give a more user-friendly version.
  202. */
  203. public function __toString() : string
  204. {
  205. return $this->name;
  206. }
  207. }