1
0
Fork 0
mirror of https://github.com/archtechx/enums.git synced 2025-12-12 08:04:04 +00:00

Optimize InvokableCases to memoize results and remove case looping

This commit is contained in:
Dan Horrigan 2022-08-25 15:49:40 -04:00 committed by Dan Horrigan
parent 373a86a16e
commit 459b4b041d
No known key found for this signature in database
GPG key ID: 96BB2CB5A161EAD5

View file

@ -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;
}
} }
throw new Exceptions\UndefinedCaseError(static::class, $name); $reflEnum = new ReflectionEnum(static::class);
if (! $reflEnum->hasCase($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()();
} }
} }