mirror of
https://github.com/archtechx/enums.git
synced 2025-12-12 09:44:03 +00:00
Optimize InvokableCases to memoize results and remove case looping
This commit is contained in:
parent
373a86a16e
commit
459b4b041d
1 changed files with 11 additions and 6 deletions
|
|
@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||||
namespace ArchTech\Enums;
|
namespace ArchTech\Enums;
|
||||||
|
|
||||||
use BackedEnum;
|
use BackedEnum;
|
||||||
|
use ReflectionEnum;
|
||||||
|
|
||||||
trait InvokableCases
|
trait InvokableCases
|
||||||
{
|
{
|
||||||
|
|
@ -17,14 +18,18 @@ trait InvokableCases
|
||||||
/** Return the enum's value or name when it's called ::STATICALLY(). */
|
/** Return the enum's value or name when it's called ::STATICALLY(). */
|
||||||
public static function __callStatic($name, $args)
|
public static function __callStatic($name, $args)
|
||||||
{
|
{
|
||||||
$cases = static::cases();
|
static $valueMap = [];
|
||||||
|
|
||||||
foreach ($cases as $case) {
|
if (isset($valueMap[$name])) {
|
||||||
if ($case->name === $name) {
|
return $valueMap[$name];
|
||||||
return $case instanceof BackedEnum ? $case->value : $case->name;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$reflEnum = new ReflectionEnum(static::class);
|
||||||
|
if (! $reflEnum->hasCase($name)) {
|
||||||
throw new Exceptions\UndefinedCaseError(static::class, $name);
|
throw new Exceptions\UndefinedCaseError(static::class, $name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get the enum case, and invoke it to get the value or name
|
||||||
|
return $valueMap[$name] = $reflEnum->getCase($name)->getValue()();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue