80 lines
2.1 KiB
PHP
80 lines
2.1 KiB
PHP
<?php
|
||
|
||
namespace goodboyalex\php_components_pack\traits;
|
||
|
||
use goodboyalex\php_components_pack\enums\MessageType;
|
||
use InvalidArgumentException;
|
||
use ReflectionEnum;
|
||
use ReflectionException;
|
||
|
||
/**
|
||
* Расширение перечислений.
|
||
*
|
||
* @author Александр Бабаев
|
||
* @package php_components_pack
|
||
* @version 1.0
|
||
* @since 1.0
|
||
*/
|
||
trait EnumExtensionsTrait
|
||
{
|
||
/**
|
||
* Получает значение перечисления по его имени.
|
||
*
|
||
* @param string $name Имя значения перечисления
|
||
*
|
||
* @return MessageType|EnumExtensionsTrait Перечисление
|
||
*/
|
||
public static function FromName (string $name): self
|
||
{
|
||
// Создаём экземпляр
|
||
$reflection = new ReflectionEnum(static::class);
|
||
|
||
// Проверяем, есть ли такая переменная
|
||
if (!$reflection->hasCase($name))
|
||
// - если нет - ошибка
|
||
throw new InvalidArgumentException(sprintf("Enumeration name '%s' does not exist!", $name));
|
||
|
||
try {
|
||
$result = $reflection->getCase($name)->getValue();
|
||
}
|
||
catch (ReflectionException) {
|
||
|
||
$result = new static();
|
||
}
|
||
|
||
return $result;
|
||
}
|
||
|
||
/**
|
||
* Получает значение перечисления
|
||
*
|
||
* @return string Значение перечисления
|
||
*/
|
||
public function GetValue (): string
|
||
{
|
||
return $this->name;
|
||
}
|
||
|
||
/**
|
||
* Конвертирует в перечисление из int.
|
||
*
|
||
* @param int $value Значение перечисления в формате int
|
||
*
|
||
* @return MessageType|EnumExtensionsTrait Объект
|
||
* перечисления
|
||
*/
|
||
public static function FromInt (int $value): self
|
||
{
|
||
return self::tryFrom($value);
|
||
}
|
||
|
||
/**
|
||
* Переводит тип в INT
|
||
*
|
||
* @return int Значение типа в INT
|
||
*/
|
||
public function ToInt (): int
|
||
{
|
||
return $this->value;
|
||
}
|
||
} |