-
-
Save crossRT/ead9901ed0c785231418727f0b74733f to your computer and use it in GitHub Desktop.
PHP Enumerated Type
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
trait HasEnums | |
{ | |
/** | |
* The array of enumerators of a given group. | |
* | |
* @param null|string $group | |
* @return array | |
*/ | |
static function enums($group = null) | |
{ | |
$constants = (new ReflectionClass(get_called_class()))->getConstants(); | |
if ($group) { | |
return array_filter($constants, function ($key) use ($group) { | |
return strpos($key, $group.'_') === 0; | |
}, ARRAY_FILTER_USE_KEY); | |
} | |
return $constants; | |
} | |
/** | |
* Check if the given value is valid within the given group. | |
* | |
* @param mixed $value | |
* @param null|string $group | |
* @return bool | |
*/ | |
static function isValidEnumValue($value, $group = null) | |
{ | |
$constants = static::enums($group); | |
return in_array($value, $constants); | |
} | |
/** | |
* Check if the given key exists. | |
* | |
* @param mixed $key | |
* @return bool | |
*/ | |
static function isValidEnumKey($key) | |
{ | |
return array_key_exists($key, static::enums()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment