Last active
November 12, 2021 16:12
-
-
Save rosstuck/38861a146509ab4cb485 to your computer and use it in GitHub Desktop.
Enums PoC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Derp; | |
abstract class Enum | |
{ | |
protected $value; | |
protected static $possibleValues; | |
protected static function getPossibleValues() | |
{ | |
if (static::$possibleValues) { | |
return static::$possibleValues; | |
} | |
$reflectionClass = new \ReflectionClass(get_called_class()); | |
static::$possibleValues = $reflectionClass->getConstants(); | |
return static::$possibleValues; | |
} | |
/** | |
* @param $name | |
* @param $arguments | |
* @return static | |
* @throws \Exception | |
*/ | |
public static function __callStatic($name, $arguments) | |
{ | |
$possibleValues = static::getPossibleValues(); | |
if (!array_key_exists($name, $possibleValues)) { | |
throw new \Exception; | |
} | |
if (count($arguments) > 0) { | |
throw new \Exception; | |
} | |
return self::createInstance($name, $possibleValues[$name]); | |
} | |
/** | |
* @param $value | |
* @return static | |
*/ | |
protected static function createInstance($value) | |
{ | |
$enum = new static; | |
$enum->value = $value; | |
return $enum; | |
} | |
protected function getValue() | |
{ | |
return $this->value; | |
} | |
public function equals(Enum $otherValue) | |
{ | |
return get_class($otherValue) === get_called_class() && $otherValue->getValue() === $this->getValue(); | |
} | |
public static function all() | |
{ | |
return array_map( | |
function($value) { | |
return static::createInstance($value); | |
}, | |
static::getPossibleValues() | |
); | |
} | |
} | |
class Day extends Enum | |
{ | |
const MONDAY = 'monday'; | |
const FRIDAY = 'friday'; | |
} | |
$monday = Day::MONDAY(); | |
var_dump($monday->equals(Day::FRIDAY())); | |
var_dump(Day::all()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment