Skip to content

Instantly share code, notes, and snippets.

@crossRT
Forked from themsaid/HasEnums.php
Created April 29, 2016 01:28
Show Gist options
  • Save crossRT/ead9901ed0c785231418727f0b74733f to your computer and use it in GitHub Desktop.
Save crossRT/ead9901ed0c785231418727f0b74733f to your computer and use it in GitHub Desktop.
PHP Enumerated Type
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