From f81e8a698b2dfd6b189accd29dc3ef30524cc802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Kv=C3=A1=C4=8Dek?= Date: Wed, 27 Jan 2016 01:53:53 +0100 Subject: [PATCH] FEATURE: enumeration can be sorted. --- app/Enumerations/BaseEnumeration.php | 42 ++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/app/Enumerations/BaseEnumeration.php b/app/Enumerations/BaseEnumeration.php index 35ffca62..4c23e441 100644 --- a/app/Enumerations/BaseEnumeration.php +++ b/app/Enumerations/BaseEnumeration.php @@ -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; } /**