AbstractEnum.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Zxing\Common;
  3. use ReflectionClass;
  4. /**
  5. * A general enum implementation until we got SplEnum.
  6. */
  7. final class AbstractEnum implements \Stringable
  8. {
  9. /**
  10. * Default value.
  11. */
  12. public const __default = null;
  13. /**
  14. * Current value.
  15. *
  16. * @var mixed
  17. */
  18. private $value;
  19. /**
  20. * Cache of constants.
  21. *
  22. * @var array<string, mixed>|null
  23. */
  24. private ?array $constants = null;
  25. /**
  26. * Creates a new enum.
  27. *
  28. * @param mixed $initialValue
  29. * @param boolean $strict
  30. */
  31. public function __construct($initialValue = null, private $strict = false)
  32. {
  33. $this->change($initialValue);
  34. }
  35. /**
  36. * Changes the value of the enum.
  37. *
  38. * @param mixed $value
  39. *
  40. * @return void
  41. */
  42. public function change($value)
  43. {
  44. if (!in_array($value, $this->getConstList(), $this->strict)) {
  45. throw new \UnexpectedValueException('Value not a const in enum ' . $this::class);
  46. }
  47. $this->value = $value;
  48. }
  49. /**
  50. * Gets all constants (possible values) as an array.
  51. *
  52. * @param boolean $includeDefault
  53. *
  54. * @return array
  55. */
  56. public function getConstList($includeDefault = true)
  57. {
  58. if ($this->constants === null) {
  59. $reflection = new ReflectionClass($this);
  60. $this->constants = $reflection->getConstants();
  61. }
  62. if ($includeDefault) {
  63. return $this->constants;
  64. }
  65. $constants = $this->constants;
  66. unset($constants['__default']);
  67. return $constants;
  68. }
  69. /**
  70. * Gets current value.
  71. *
  72. * @return mixed
  73. */
  74. public function get()
  75. {
  76. return $this->value;
  77. }
  78. /**
  79. * Gets the name of the enum.
  80. *
  81. * @return string
  82. */
  83. public function __toString(): string
  84. {
  85. return (string)array_search($this->value, $this->getConstList());
  86. }
  87. }