File tree 2 files changed +16
-6
lines changed
2 files changed +16
-6
lines changed Original file line number Diff line number Diff line change @@ -28,6 +28,13 @@ abstract class Enum implements \JsonSerializable
28
28
*/
29
29
protected $ value ;
30
30
31
+ /**
32
+ * Enum key, the constant name
33
+ *
34
+ * @var string
35
+ */
36
+ private $ key ;
37
+
31
38
/**
32
39
* Store existing constants in a static cache per object.
33
40
*
@@ -61,7 +68,7 @@ public function __construct($value)
61
68
$ value = $ value ->getValue ();
62
69
}
63
70
64
- static ::assertValidValue ($ value );
71
+ $ this -> key = static ::assertValidValue ($ value );
65
72
66
73
/** @psalm-var T */
67
74
$ this ->value = $ value ;
@@ -94,9 +101,9 @@ public function getValue()
94
101
*
95
102
* @psalm-pure
96
103
*/
97
- public function getKey (): string
104
+ public function getKey ()
98
105
{
99
- return static ::search ($ this ->value );
106
+ return $ this -> key ?? ( $ this -> key = static ::search ($ this ->value ) );
100
107
}
101
108
102
109
/**
@@ -198,11 +205,13 @@ public static function isValid($value)
198
205
* @psalm-pure
199
206
* @psalm-assert T $value
200
207
*/
201
- private static function assertValidValue ($ value ): void
208
+ private static function assertValidValue ($ value ): string
202
209
{
203
- if (! static ::isValid ($ value )) {
210
+ if (false === ( $ key = static ::search ($ value) )) {
204
211
throw new \UnexpectedValueException ("Value ' $ value' is not part of the enum " . static ::class);
205
212
}
213
+
214
+ return $ key ;
206
215
}
207
216
208
217
/**
Original file line number Diff line number Diff line change @@ -324,7 +324,8 @@ public function testSerialize()
324
324
{
325
325
// split string for Pretty CI: "Line exceeds 120 characters"
326
326
$ bin = '4f3a33303a224d79434c6162735c54657374735c456e756d5c456e756d4669787 ' .
327
- '4757265223a313a7b733a383a22002a0076616c7565223b733a333a22666f6f223b7d ' ;
327
+ '4757265223a323a7b733a383a22002a0076616c7565223b733a333a22666f6f223b73 ' .
328
+ '3a32323a22004d79434c6162735c456e756d5c456e756d006b6579223b733a333a22464f4f223b7d ' ;
328
329
329
330
$ this ->assertEquals ($ bin , bin2hex (serialize (EnumFixture::FOO ())));
330
331
}
You can’t perform that action at this time.
0 commit comments