Skip to content

Instantly share code, notes, and snippets.

@CamKem
Created September 1, 2023 09:34
Show Gist options
  • Save CamKem/3981f0d0f7a156c6f39b017891ccca08 to your computer and use it in GitHub Desktop.
Save CamKem/3981f0d0f7a156c6f39b017891ccca08 to your computer and use it in GitHub Desktop.
Group of enum helper methods trait
<?php
namespace App\Traits;
use Exception;
trait EnumMethods
{
/**
* Return the enum value from the name.
* @return array
*/
public static function toNames(): array
{
return array_column(self::cases(), 'name');
}
/**
* Return the enum value from the name.
* @param $name
* @return string
*/
public static function value($name): string
{
return self::from($name)->value;
}
/**
* Return an array with the key as the value and the value as the name.
*/
public static function toValues(): array
{
return array_column(self::cases(), 'value');
}
/**
* Return an array with the key as the name and the value as the value.
*/
public static function toArray(): array
{
return array_combine(self::toNames(), self::toValues());
}
/**
* Invoked when a non-existent or inaccessible method is called on an object of this class.
* @throws Exception
*/
public static function __callStatic(string $method, array $parameters): mixed
{
$method = ucfirst($method);
if (in_array($method, self::toValues(), true)) {
$method = strtoupper($method);
return constant(self::class . "::{$method}")->value;
}
return throw new Exception('Unknown method: ' . $method);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment