Skip to content

Commit d178027

Browse files
authored
Merge pull request #129 from iFixit/cache-instances
__callStatic: cache created Enum instances
2 parents a1fd916 + 14edb7b commit d178027

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

Diff for: src/Enum.php

+17-6
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ abstract class Enum implements \JsonSerializable
3737
*/
3838
protected static $cache = [];
3939

40+
/**
41+
* Cache of instances of the Enum class
42+
*
43+
* @var array
44+
* @psalm-var array<class-string, array<string, static>>
45+
*/
46+
protected static $instances = [];
47+
4048
/**
4149
* Creates a new value of some type
4250
*
@@ -211,17 +219,20 @@ public static function search($value)
211219
* @param array $arguments
212220
*
213221
* @return static
214-
* @psalm-pure
215222
* @throws \BadMethodCallException
216223
*/
217224
public static function __callStatic($name, $arguments)
218225
{
219-
$array = static::toArray();
220-
if (isset($array[$name]) || \array_key_exists($name, $array)) {
221-
return new static($array[$name]);
226+
$class = static::class;
227+
if (!isset(self::$instances[$class][$name])) {
228+
$array = static::toArray();
229+
if (!isset($array[$name]) && !\array_key_exists($name, $array)) {
230+
$message = "No static method or enum constant '$name' in class " . static::class;
231+
throw new \BadMethodCallException($message);
232+
}
233+
return self::$instances[$class][$name] = new static($array[$name]);
222234
}
223-
224-
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . static::class);
235+
return clone self::$instances[$class][$name];
225236
}
226237

227238
/**

Diff for: tests/EnumTest.php

+1
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ public function testStaticAccess()
143143
$this->assertEquals(new EnumFixture(EnumFixture::FOO), EnumFixture::FOO());
144144
$this->assertEquals(new EnumFixture(EnumFixture::BAR), EnumFixture::BAR());
145145
$this->assertEquals(new EnumFixture(EnumFixture::NUMBER), EnumFixture::NUMBER());
146+
$this->assertNotSame(EnumFixture::NUMBER(), EnumFixture::NUMBER());
146147
}
147148

148149
/**

0 commit comments

Comments
 (0)