php_components_pack/sources/traits/EnumExtensionsTrait.php
2025-02-03 18:49:47 +03:00

80 lines
2.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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;
}
}