Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ abstract class Enum implements \JsonSerializable
*/
protected static $cache = [];

/**
* Cache of instances of the Enum class
*
* @var array
* @psalm-var array<class-string, array<string, static>>
*/
protected static $instances = [];

/**
* Creates a new value of some type
*
Expand Down Expand Up @@ -211,17 +219,20 @@ public static function search($value)
* @param array $arguments
*
* @return static
* @psalm-pure
* @throws \BadMethodCallException
*/
public static function __callStatic($name, $arguments)
{
$array = static::toArray();
if (isset($array[$name]) || \array_key_exists($name, $array)) {
return new static($array[$name]);
$class = static::class;
if (!isset(self::$instances[$class][$name])) {
$array = static::toArray();
if (!isset($array[$name]) && !\array_key_exists($name, $array)) {
$message = "No static method or enum constant '$name' in class " . static::class;
throw new \BadMethodCallException($message);
}
return self::$instances[$class][$name] = new static($array[$name]);
}

throw new \BadMethodCallException("No static method or enum constant '$name' in class " . static::class);
return self::$instances[$class][$name];
}

/**
Expand Down