This commit is contained in:
2025-02-03 18:49:47 +03:00
parent f1a79d66ec
commit dd62ad0ca4
1739 changed files with 154102 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
<?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;
}
}