Last active
September 10, 2020 13:25
-
-
Save vertexvaar/686e3c8b98804d0bf3e1d804ad5a2ee5 to your computer and use it in GitHub Desktop.
"Das war zu einfach" - Sorin
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 | |
declare(strict_types=1); | |
function assertConstantOfClass(string $class, $constantValue): void | |
{ | |
$reflection = new ReflectionClass($class); | |
$constants = $reflection->getConstants(); | |
foreach ($constants as $value) { | |
if ($value === $constantValue) { | |
return; | |
} | |
} | |
throw new Exception(sprintf('The value "%s" is not defined as a constant of class "%s"', $constantValue, $class)); | |
} | |
echo '----------------------- ENUMS'; | |
abstract class Enum | |
{ | |
/** @var mixed */ | |
private $value; | |
/** @param mixed $value */ | |
final private function __construct($value) | |
{ | |
$this->value = $value; | |
} | |
final public static function __callStatic($name, $arguments) | |
{ | |
$constant = 'static::' . $name; | |
if (defined($constant)) { | |
return new static(constant($constant)); | |
} | |
throw new LogicException(sprintf('The enum "%s" does not contain "%s"', static::class, $name)); | |
} | |
} | |
/** | |
* @method MyEnum FOO() | |
* @method MyEnum BAR() | |
*/ | |
final class MyEnum extends Enum | |
{ | |
protected const FOO = 'FOO'; | |
protected const BAR = 'BAR'; | |
} | |
/** | |
* @method YourEnum FOO() | |
* @method YourEnum BAR() | |
*/ | |
final class YourEnum extends Enum | |
{ | |
protected const FOO = 'FOO'; | |
protected const BAR = 'BAR'; | |
} | |
function compareFunc(Enum $type): bool | |
{ | |
return $type == MyEnum::FOO(); | |
} | |
var_dump(compareFunc(MyEnum::FOO())); | |
var_dump(compareFunc(MyEnum::BAR())); | |
var_dump(compareFunc(YourEnum::FOO())); | |
var_dump(compareFunc(YourEnum::BAR())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment