Skip to content

Instantly share code, notes, and snippets.

@vatson
Forked from makasim/gist:1089373
Created July 18, 2011 13:06
Show Gist options
  • Save vatson/1089447 to your computer and use it in GitHub Desktop.
Save vatson/1089447 to your computer and use it in GitHub Desktop.
enum
<?php
namespace Rj\CoreBundle\Enum;
abstract class Enum
{
/**
*
* @var array
*/
protected static $titles = array();
/**
*
* @var Closure
*/
protected static $translator;
public static function all()
{
static::checkIntegrity();
return static::getRC()->getConstants();
}
/**
*
* @return array
*/
public static function values()
{
static::checkIntegrity();
return array_values(static::all());
}
public static function keys()
{
static::checkIntegrity();
return array_keys(static::all());
}
/**
*
* @return array
*/
public static function titles()
{
static::checkIntegrity();
$titles = static::$titles;
return array_map(static::$titles, self::getTranslator());
}
/**
*
* @param string|int $value
*
* @return bool
*/
public static function isValid($value)
{
static::checkIntegrity();
return \in_array($value, static::all(), false);
}
/**
*
* @param mixed $value
*
* @throws Exception if the value does not valid for the enum type
*
* @return void
*/
public static function throwsInvalid($value)
{
if (!static::isValid($value)) {
throw new \Exception('The enum type `' . get_called_class() . '` does not contains value `' . var_export($value, true) . '`. Possible values are `' . static::implode('`, `') . '`');
}
}
/**
*
* @param string $separator
*
* @return string
*/
public static function implode($separator = ', ')
{
return implode($separator, static::values());
}
public static function setTranslator(\Closure $tranlator)
{
self::$translator = $translator;
}
public static function getTranslator()
{
if (false == self::$translator) {
self::$translator = function($title) {
return $title;
};
}
return self::$translator;
}
/**
*
* @return \ReflectionClass
*/
protected static function getRC() {
return new \ReflectionClass(get_called_class());
}
protected static function checkIntegrity()
{
static $checked = false;
if (true == $checked) return;
$diff = \array_diff_key(static::getRC()->getConstants(), static::$titles);
if (false == empty($diff)) {
throw new \LengthException('The enum `'.\get_called_class().'` is not configured correctly. There is a diff between titles and defenitino `'.\json_encode($diff).'`');
}
$checked = true;
}
}
class Enum_Doctrine_Extension
{
function makeMeHappy()
{
die;
}
}
@makasim
Copy link

makasim commented Jul 18, 2011

highwayman!

@vatson
Copy link
Author

vatson commented Jul 18, 2011

Enough to shit on my fork!

@makasim
Copy link

makasim commented Jul 18, 2011

cannot obey to shit a little here

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