Skip to content

Instantly share code, notes, and snippets.

@caiovncius
Created December 26, 2023 02:20
Show Gist options
  • Save caiovncius/97f24dd52c1eb5c478a18cd4811cf421 to your computer and use it in GitHub Desktop.
Save caiovncius/97f24dd52c1eb5c478a18cd4811cf421 to your computer and use it in GitHub Desktop.
Trait with common functions for enums.
<?php
declare(strict_types=1);
namespace App\Traits\Components;
trait Enums
{
/**
* @return array
*/
public static function names(): array
{
return array_column(self::cases(), 'name');
}
/**
* @return array
*/
public static function values(): array
{
return array_column(self::cases(), 'value');
}
/**
* @return array
*/
public static function toArray(): array
{
return array_combine(self::values(), self::names());
}
/**
* @param string $name
*
* @return mixed
*/
public static function fromName(string $name): ?self
{
if (in_array($name, self::names())) {
return self::from($name);
}
return null;
}
/**
* @param string $value
*
* @return mixed
*/
public static function fromValue(string $value): ?self
{
if (in_array($value, self::values())) {
return self::from($value);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment