Skip to content

Instantly share code, notes, and snippets.

@jwhulette
Forked from aneesdev/EnhancedEnum.php
Created September 22, 2022 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwhulette/623ab5e401213a0fb42cd5cfa59b0904 to your computer and use it in GitHub Desktop.
Save jwhulette/623ab5e401213a0fb42cd5cfa59b0904 to your computer and use it in GitHub Desktop.
EnhancedEnum PHP trait
<?php
trait EnhancedEnum
{
/**
* Get the enum value from the name. e.g case INVOICE = 'invoice'; will return 'invoice'
*
* @param string $name
* @return static
*/
public static function fromName(string $name): static
{
$reflection = new \ReflectionEnum(static::class);
return $reflection->hasCase($name)
? $reflection->getCase($name)->getValue()
: null;
}
/**
* Get the enum names as an array.
*
* @return array
*/
public static function toNames(): array
{
return array_column(self::cases(), 'name');
}
/**
* Get the enum values as an array.
*
* @return array
*/
public static function toValues(): array
{
return array_column(self::cases(), 'value');
}
/**
* Get the enum as an array. e.g ['INVOICE' => 'invoice']
*
* @return array
*/
public static function toArray(): array
{
return array_combine(self::toNames(), self::toValues());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment