Skip to content

Commit 34247d1

Browse files
committed
Merge branch 'master' into improve_getKey_performance
2 parents 86949d6 + 616601d commit 34247d1

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

src/Enum.php

Lines changed: 17 additions & 7 deletions
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
*
@@ -54,7 +62,6 @@ public function __construct($value)
5462
}
5563

5664
if (!$this->isValid($value)) {
57-
/** @psalm-suppress InvalidCast */
5865
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class);
5966
}
6067

@@ -210,17 +217,20 @@ public static function search($value)
210217
* @param array $arguments
211218
*
212219
* @return static
213-
* @psalm-pure
214220
* @throws \BadMethodCallException
215221
*/
216222
public static function __callStatic($name, $arguments)
217223
{
218-
$array = static::toArray();
219-
if (isset($array[$name]) || \array_key_exists($name, $array)) {
220-
return new static($array[$name]);
224+
$class = static::class;
225+
if (!isset(self::$instances[$class][$name])) {
226+
$array = static::toArray();
227+
if (!isset($array[$name]) && !\array_key_exists($name, $array)) {
228+
$message = "No static method or enum constant '$name' in class " . static::class;
229+
throw new \BadMethodCallException($message);
230+
}
231+
return self::$instances[$class][$name] = new static($array[$name]);
221232
}
222-
223-
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . static::class);
233+
return clone self::$instances[$class][$name];
224234
}
225235

226236
/**

tests/EnumTest.php

Lines changed: 1 addition & 0 deletions
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)