@@ -37,6 +37,14 @@ abstract class Enum implements \JsonSerializable
37
37
*/
38
38
protected static $ cache = [];
39
39
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
+
40
48
/**
41
49
* Creates a new value of some type
42
50
*
@@ -54,7 +62,6 @@ public function __construct($value)
54
62
}
55
63
56
64
if (!$ this ->isValid ($ value )) {
57
- /** @psalm-suppress InvalidCast */
58
65
throw new \UnexpectedValueException ("Value ' $ value' is not part of the enum " . static ::class);
59
66
}
60
67
@@ -210,17 +217,20 @@ public static function search($value)
210
217
* @param array $arguments
211
218
*
212
219
* @return static
213
- * @psalm-pure
214
220
* @throws \BadMethodCallException
215
221
*/
216
222
public static function __callStatic ($ name , $ arguments )
217
223
{
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 ]);
221
232
}
222
-
223
- throw new \BadMethodCallException ("No static method or enum constant ' $ name' in class " . static ::class);
233
+ return clone self ::$ instances [$ class ][$ name ];
224
234
}
225
235
226
236
/**
0 commit comments