-
-
Save yekowele/4148c93bc2229db7af99db5d5e4d93c1 to your computer and use it in GitHub Desktop.
EnhancedEnum PHP trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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