Created
April 30, 2018 15:04
-
-
Save kobus1998/7180bb49ad1998a2c483d2856b0788dc to your computer and use it in GitHub Desktop.
Enum in php
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 | |
class Enum { | |
private static $constCacheArray = NULL; | |
private static function getConstants() { | |
if (self::$constCacheArray == NULL) { | |
self::$constCacheArray = []; | |
} | |
$calledClass = get_called_class(); | |
if (!array_key_exists($calledClass, self::$constCacheArray)) { | |
$reflect = new ReflectionClass($calledClass); | |
self::$constCacheArray[$calledClass] = $reflect->getConstants(); | |
} | |
return self::$constCacheArray[$calledClass]; | |
} | |
public static function isValidName($name, $strict = false) { | |
$constants = self::getConstants(); | |
if ($strict) { | |
return array_key_exists($name, $constants); | |
} | |
$keys = array_map('strtolower', array_keys($constants)); | |
return in_array(strtolower($name), $keys); | |
} | |
public static function isValidValue($value, $strict = true) { | |
$values = array_values(self::getConstants()); | |
return in_array($value, $values, $strict); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment