Files
core/app/Enumerations/BaseEnumeration.php
T
Michal Kváček bc2bdd38b9 FIX: fix multiple enumeration classes
Enumeration classes shared one static variable which caused sharing data. Main problem was with conflicts in names. This commit divides enumeration into "namespaces". Used namespace is return value from "get_called_class()" function.
2016-01-26 23:19:42 +01:00

86 lines
2.2 KiB
PHP

<?php
namespace App\Enumerations;
use App\Enumerations\Exceptions\EnumerationExistsException;
abstract class BaseEnumeration
{
public static $items = [];
/**
* Init enumerations
*/
protected static function init()
{
if (!isset(self::$items[get_called_class()]) || empty(self::$items[get_called_class()])) {
$className = get_called_class();
if (method_exists($className, 'init')) {
$className::init();
}
}
}
/**
* Add new item into enumeration
*
* @param $key
* @param $translation
* @param bool|false $overwrite
*
* @throws EnumerationExistsException
*/
public static function push($key, $translation, $overwrite = false)
{
// item exists and we do not want to overwrite items
if (!$overwrite && isset(self::$items[get_called_class()][$key])) {
throw new EnumerationExistsException(get_called_class() . ': ' . $key . ' already in ' . $translation);
}
// if given collection does not exists, create empty one
if (!isset(self::$items[get_called_class()])) {
self::$items[get_called_class()] = [];
}
// add to collection
self::$items[get_called_class()][$key] = $translation;
}
/**
* Return count of all items in collection
*
* @return int
*/
public static function getCount()
{
return count(self::getWithTranslations());
}
/**
* Getter for all enumeration items in iven collection.
*
* Return value is associative array indexed by item "name". Value of each field is its translation (translation
* string, e.g. admin/mainMenu.something)
*
* @return array
*/
public static function getWithTranslations()
{
if (!isset(self::$items[get_called_class()]) || empty(self::$items[get_called_class()])) {
self::init();
}
return self::$items[get_called_class()];
}
/**
* Getter for list of all enumeration items.
*
* @return array
*/
public static function getSimple()
{
return array_keys(self::getWithTranslations());
}
}