Created
December 26, 2023 02:20
-
-
Save caiovncius/97f24dd52c1eb5c478a18cd4811cf421 to your computer and use it in GitHub Desktop.
Trait with common functions for enums.
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 | |
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