Skip to content

Instantly share code, notes, and snippets.

@66Ton99
Last active August 29, 2015 14:10
Show Gist options
  • Save 66Ton99/910dda1656e01f4c47a6 to your computer and use it in GitHub Desktop.
Save 66Ton99/910dda1656e01f4c47a6 to your computer and use it in GitHub Desktop.
OOP enum realisation
<?php
use InvalidArgumentException;
use ReflectionClass;
/**
* Base Enum class
* Require PHP >= 5.3
*
* @author Ton Sharp <66ton99@gmail.com>
*/
abstract class Enum
{
/**
* @return array
*/
public static function all()
{
$reflection = static::getRC();
$buffer = $reflection->getConstants();
foreach (array($reflection->getParentClass()) + $reflection->getInterfaces() as $fill) {
$buffer = array_diff_key($buffer, $fill->getConstants());
}
return $buffer;
}
/**
* Values
*
* @return array
*/
public static function values()
{
return array_values(static::all());
}
/**
* Keys
*
* @return array
*/
public static function keys()
{
return array_keys(static::all());
}
/**
* Check value
*
* @param string|int $value
*
* @return bool
*/
public static function isValid($value)
{
return in_array($value, static::all(), false);
}
/**
* Check value with exception on fail
*
* @param mixed $value
*
* @throws InvalidArgumentException if the value does not valid for the enum type
*
* @return void
*/
public static function throwsInvalid($value)
{
if (!static::isValid($value)) {
throw new InvalidArgumentException(
sprintf(
'The enum type `%s` does not contains value `%s` . Possible values are `%s`',
get_called_class(),
var_export($value, true),
static::implode(', ', '`')
)
);
}
}
/**
* Implode all values to the string separated by $separator
*
* @param string $separator
* @param string $quoteSymbol
*
* @return string
*/
public static function implode($separator = ',', $quoteSymbol = '\'')
{
return $quoteSymbol . implode($quoteSymbol . $separator . $quoteSymbol, static::values()) . $quoteSymbol;
}
/**
* Get reflection class
*
* @return ReflectionClass
*/
protected static function getRC()
{
return new ReflectionClass(get_called_class());
}
/**
* Get default values by default it is first element
*
* @return string
*/
public static function defaultValue()
{
$values = (static::values());
return array_shift($values);
}
}
@66Ton99
Copy link
Author

66Ton99 commented Dec 1, 2014

Example

class Enums extends Enum
{
    FIRST = 1;
    SECOND = 2;
    THIRD = 3;
}

Usage

var_dump(Enums::all());
var_dump(Enums::implode());

@66Ton99
Copy link
Author

66Ton99 commented Dec 2, 2014

Maybe better to use it https://github.com/marc-mabe/php-enum because it allows you to use type hinting and more...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment