AbstractEnum.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace Zxing\Common;
  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. *
  48. * @return void
  49. */
  50. public function change($value)
  51. {
  52. if (!in_array($value, $this->getConstList(), $this->strict)) {
  53. throw new \UnexpectedValueException('Value not a const in enum ' . get_class($this));
  54. }
  55. $this->value = $value;
  56. }
  57. /**
  58. * Gets all constants (possible values) as an array.
  59. *
  60. * @param boolean $includeDefault
  61. *
  62. * @return array
  63. */
  64. public function getConstList($includeDefault = true)
  65. {
  66. if ($this->constants === null) {
  67. $reflection = new ReflectionClass($this);
  68. $this->constants = $reflection->getConstants();
  69. }
  70. if ($includeDefault) {
  71. return $this->constants;
  72. }
  73. $constants = $this->constants;
  74. unset($constants['__default']);
  75. return $constants;
  76. }
  77. /**
  78. * Gets current value.
  79. *
  80. * @return mixed
  81. */
  82. public function get()
  83. {
  84. return $this->value;
  85. }
  86. /**
  87. * Gets the name of the enum.
  88. *
  89. * @return string
  90. */
  91. public function __toString()
  92. {
  93. return (string)array_search($this->value, $this->getConstList());
  94. }
  95. }