Skip to content

Instantly share code, notes, and snippets.

@yekowele
Forked from aneesdev/EnhancedEnum.php
Created September 19, 2022 20:15
Show Gist options
  • Save yekowele/4148c93bc2229db7af99db5d5e4d93c1 to your computer and use it in GitHub Desktop.
Save yekowele/4148c93bc2229db7af99db5d5e4d93c1 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