Skip to content

Commit

Permalink
Merge pull request #129 from iFixit/cache-instances
Browse files Browse the repository at this point in the history
__callStatic: cache created Enum instances
  • Loading branch information
mnapoli authored Nov 14, 2020
2 parents a1fd916 + 14edb7b commit d178027
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
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

0 comments on commit d178027

Please sign in to comment.