123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205 |
- <?php
- namespace MyCLabs\Enum;
- abstract class Enum implements \JsonSerializable
- {
-
- protected $value;
-
- protected static $cache = [];
-
- public function __construct($value)
- {
- if ($value instanceof static) {
- $value = $value->getValue();
- }
- if (!$this->isValid($value)) {
- throw new \UnexpectedValueException("Value '$value' is not part of the enum " . \get_called_class());
- }
- $this->value = $value;
- }
-
- public function getValue()
- {
- return $this->value;
- }
-
- public function getKey()
- {
- return static::search($this->value);
- }
-
- public function __toString()
- {
- return (string)$this->value;
- }
-
- final public function equals($variable = null): bool
- {
- return $variable instanceof self
- && $this->getValue() === $variable->getValue()
- && \get_called_class() === \get_class($variable);
- }
-
- public static function keys()
- {
- return \array_keys(static::toArray());
- }
-
- public static function values()
- {
- $values = array();
- foreach (static::toArray() as $key => $value) {
- $values[$key] = new static($value);
- }
- return $values;
- }
-
- public static function toArray()
- {
- $class = \get_called_class();
- if (!isset(static::$cache[$class])) {
- $reflection = new \ReflectionClass($class);
- static::$cache[$class] = $reflection->getConstants();
- }
- return static::$cache[$class];
- }
-
- public static function isValid($value)
- {
- return \in_array($value, static::toArray(), true);
- }
-
- public static function isValidKey($key)
- {
- $array = static::toArray();
- return isset($array[$key]) || \array_key_exists($key, $array);
- }
-
- public static function search($value)
- {
- return \array_search($value, static::toArray(), true);
- }
-
- public static function __callStatic($name, $arguments)
- {
- $array = static::toArray();
- if (isset($array[$name]) || \array_key_exists($name, $array)) {
- return new static($array[$name]);
- }
- throw new \BadMethodCallException("No static method or enum constant '$name' in class " . \get_called_class());
- }
-
- public function jsonSerialize()
- {
- return $this->getValue();
- }
- }
|