Skip to content

Instantly share code, notes, and snippets.

@do-aki
Last active Mar 4, 2018
Embed
What would you like to do?
<?php
trait EnumTrait
{
/** @var static[] */
private static $instance;
/** @var mixed value of constant */
private $value;
/**
* Enum constructor.
*
* @param mixed $value value of constant
*/
private function __construct($value)
{
$ref = new ReflectionObject($this);
$cons = $ref->getConstants();
if (!in_array($value, $cons, true)) {
throw new InvalidArgumentException("invalid constant value");
}
$this->value = $value;
}
/**
* return value of constant
*
* @return mixed
*/
final public function value()
{
return $this->value;
}
/**
* return true if same constant
*
* @return bool
*/
final public function is(self $lhs){
return $this === $lhs;
}
/**
* return enum constant with the specified value
*
* @param mixed $value
* @return self
*/
final public static function valueOf($value)
{
$cls = __CLASS__;
foreach ((new ReflectionClass($cls))->getConstants() as $name => $const_value) {
if ($const_value === $value) {
return $cls::$name();
}
}
throw new InvalidArgumentException("invalid constant value");
}
/**
* @return self
*/
private static function constant()
{
static $name = null;
if ($name === null) {
$name = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['function'];
}
if (!isset(self::$instance[$name])) {
$cls = __CLASS__;
self::$instance[$name] = new $cls(constant("{$cls}::{$name}"));
}
return self::$instance[$name];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment