Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. <?php declare(strict_types=1);
  2.  
  3. namespace App;
  4.  
  5. trait Enumerated
  6. {
  7. /**
  8. * @var array<string, self>
  9. */
  10. private static $values = [];
  11.  
  12. /**
  13. * @var string
  14. */
  15. private $value;
  16.  
  17. private function __construct(string $value)
  18. {
  19. $this->value = $value;
  20. }
  21.  
  22. /**
  23. * @return self[]
  24. */
  25. public static function values(): array
  26. {
  27. if (!self::$values) {
  28. self::init();
  29. }
  30.  
  31. return array_values(self::$values);
  32. }
  33.  
  34. public function equals(self $enum): bool
  35. {
  36. return $this->value === $enum->value;
  37. }
  38.  
  39. public function __toString(): string
  40. {
  41. return $this->value;
  42. }
  43.  
  44. public static function fromString(string $value): self
  45. {
  46. if (!self::$values) {
  47. self::init();
  48. }
  49.  
  50. if (!isset(self::$values[$value])) {
  51. throw new EnumException(sprintf('invalid value "%s"', $value));
  52. }
  53.  
  54. return self::$values[$value];
  55. }
  56.  
  57. private static function get(string $value): self
  58. {
  59. if (!self::$values) {
  60. self::init();
  61. }
  62.  
  63. return self::$values[$value];
  64. }
  65.  
  66. private static function init()
  67. {
  68. foreach ((new \ReflectionClass(static::class))->getReflectionConstants() as $name => $constantReflection) {
  69. $constantValue = $constantReflection->getValue();
  70.  
  71. if (in_array($constantValue, self::$values, true)) {
  72. throw new EnumException(sprintf('duplicated value "%s"', $constantValue));
  73. }
  74.  
  75. self::$values[$constantValue] = new static($constantValue);
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement