File tree Expand file tree Collapse file tree 2 files changed +16
-6
lines changed Expand file tree Collapse file tree 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
2828 */
2929 protected $ value ;
3030
31+ /**
32+ * Enum key, the constant name
33+ *
34+ * @var string
35+ */
36+ private $ key ;
37+
3138 /**
3239 * Store existing constants in a static cache per object.
3340 *
@@ -61,7 +68,7 @@ public function __construct($value)
6168 $ value = $ value ->getValue ();
6269 }
6370
64- static ::assertValidValue ($ value );
71+ $ this -> key = static ::assertValidValue ($ value );
6572
6673 /** @psalm-var T */
6774 $ this ->value = $ value ;
@@ -94,9 +101,9 @@ public function getValue()
94101 *
95102 * @psalm-pure
96103 */
97- public function getKey (): string
104+ public function getKey ()
98105 {
99- return static ::search ($ this ->value );
106+ return $ this -> key ?? ( $ this -> key = static ::search ($ this ->value ) );
100107 }
101108
102109 /**
@@ -198,11 +205,13 @@ public static function isValid($value)
198205 * @psalm-pure
199206 * @psalm-assert T $value
200207 */
201- private static function assertValidValue ($ value ): void
208+ private static function assertValidValue ($ value ): string
202209 {
203- if (! static ::isValid ($ value )) {
210+ if (false === ( $ key = static ::search ($ value) )) {
204211 throw new \UnexpectedValueException ("Value ' $ value' is not part of the enum " . static ::class);
205212 }
213+
214+ return $ key ;
206215 }
207216
208217 /**
Original file line number Diff line number Diff line change @@ -324,7 +324,8 @@ public function testSerialize()
324324 {
325325 // split string for Pretty CI: "Line exceeds 120 characters"
326326 $ bin = '4f3a33303a224d79434c6162735c54657374735c456e756d5c456e756d4669787 ' .
327- '4757265223a313a7b733a383a22002a0076616c7565223b733a333a22666f6f223b7d ' ;
327+ '4757265223a323a7b733a383a22002a0076616c7565223b733a333a22666f6f223b73 ' .
328+ '3a32323a22004d79434c6162735c456e756d5c456e756d006b6579223b733a333a22464f4f223b7d ' ;
328329
329330 $ this ->assertEquals ($ bin , bin2hex (serialize (EnumFixture::FOO ())));
330331 }
You can’t perform that action at this time.
0 commit comments