Created
April 2, 2017 19:25
-
-
Save voskobovich/b65e46a4510955feb3500fa5d29879d7 to your computer and use it in GitHub Desktop.
Yii2 Enum
This file contains 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
/** | |
* 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