PHP Class to have enum with helper methods
<?php
/**
* SampleEnum extending BaseEnum
* @author Javier Sampedro <jsampedro77@gmail.com>
*/
class SampleEnum extends BaseEnum
{
CONST COMUNICATION_ERROR = 1;
CONST EXCESIVE_TIME = 2;
CONST SHOT_TRACE = 4;
CONST LONG_TEST = 8;
CONST TURNED_OFF = 16;
}
<?php
class BaseEnum
{
/**
* Gets all constants
*
* @return array
*/
public static function toArray() {
$class = new \ReflectionClass(get_called_class());
return $class->getConstants();
}
/**
* Gets all constant values
*
* @return array
*/
public static function values() {
$class = new \ReflectionClass(get_called_class());
return array_flip($class->getConstants());
}
/**
* Gets an array with value => humanized constant name
*
* @return array
*/
public static function humanizedValues() {
$values = self::values();
foreach ($values as $k => &$v) {
$v = trim(strtolower($v));
$v = preg_replace('/_/', ' ', $v);
$v = explode(' ', $v);
$v = array_map('ucwords', $v);
$v = implode(' ', $v);
}
return $values;
}
}