Skip to content

Instantly share code, notes, and snippets.

@aneesdev
Created September 19, 2022 18:59
Show Gist options
  • Save aneesdev/909f96993ade4817956265b04bc4e621 to your computer and use it in GitHub Desktop.
Save aneesdev/909f96993ade4817956265b04bc4e621 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