Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save voskobovich/b65e46a4510955feb3500fa5d29879d7 to your computer and use it in GitHub Desktop.
Save voskobovich/b65e46a4510955feb3500fa5d29879d7 to your computer and use it in GitHub Desktop.
Yii2 Enum
/**
* Class BaseEnum.
*/
abstract class BaseEnum
{
/**
* Get All Labels
* @return array
*/
public static function getLabels(): array
{
$reflectionClass = new \ReflectionClass(__CLASS__);
$labels = [];
foreach ($reflectionClass->getConstants() as $constantName => $constantValue) {
$constantName = str_replace('_', ' ', $constantName);
$constantName = strtolower($constantName);
$labels[$constantValue] = ucwords($constantName);
}
return $labels;
}
/**
* Get Keys
* @return array
*/
public static function getKeys(): array
{
$items = self::getLabels();
return array_keys($items);
}
/**
* Get Label by Key
* @param $key
* @return string
*/
public static function getLabelByKey($key): string
{
$items = self::getLabels();
return $items[$key] ?? $key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment