FEATURE: enumeration can be sorted.

This commit is contained in:
Michal Kváček
2016-01-27 01:53:53 +01:00
parent bc2bdd38b9
commit f81e8a698b
+36 -6
View File
@@ -5,19 +5,28 @@ use App\Enumerations\Exceptions\EnumerationExistsException;
abstract class BaseEnumeration
{
protected static $initiliazed = [];
public static $items = [];
const ORDER_BY_KEY = 1;
const ORDER_BY_KEY_DESC = 2;
const ORDER_BY_TEXT = 4;
const ORDER_BY_TEXT_DESC = 8;
/**
* Init enumerations
*/
protected static function init()
{
if (!isset(self::$items[get_called_class()]) || empty(self::$items[get_called_class()])) {
$className = get_called_class();
$className = get_called_class();
if (!in_array($className, self::$initiliazed)) {
// try to call init() method
if (method_exists($className, 'init')) {
$className::init();
}
self::$initiliazed[] = $className;
}
}
@@ -43,7 +52,7 @@ abstract class BaseEnumeration
}
// add to collection
self::$items[get_called_class()][$key] = $translation;
self::$items[get_called_class()][$key] = trans($translation);
}
/**
@@ -62,15 +71,36 @@ abstract class BaseEnumeration
* Return value is associative array indexed by item "name". Value of each field is its translation (translation
* string, e.g. admin/mainMenu.something)
*
* @param string $orderBy
*
* @return array
*/
public static function getWithTranslations()
public static function getWithTranslations($orderBy = self::ORDER_BY_KEY)
{
if (!isset(self::$items[get_called_class()]) || empty(self::$items[get_called_class()])) {
// if not initialized yet, init this enumerration
if (!in_array(get_called_class(), self::$initiliazed)) {
self::init();
}
return self::$items[get_called_class()];
$items = self::$items[get_called_class()];
// order results
switch ($orderBy) {
case self::ORDER_BY_KEY:
ksort($items);
break;
case self::ORDER_BY_KEY_DESC:
krsort($items);
break;
case self::ORDER_BY_TEXT:
sort($items);
break;
case self::ORDER_BY_TEXT_DESC:
rsort($items);
break;
}
return $items;
}
/**