AbstractEnum.php 2.0 KB

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