Skip to content

__callStatic: cache created Enum instances #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 14, 2020
Merged
Show file tree
Hide file tree
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 clone self::$instances[$class][$name];
}

/**
Expand Down
1 change: 1 addition & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ public function testStaticAccess()
$this->assertEquals(new EnumFixture(EnumFixture::FOO), EnumFixture::FOO());
$this->assertEquals(new EnumFixture(EnumFixture::BAR), EnumFixture::BAR());
$this->assertEquals(new EnumFixture(EnumFixture::NUMBER), EnumFixture::NUMBER());
$this->assertNotSame(EnumFixture::NUMBER(), EnumFixture::NUMBER());
}

/**
Expand Down