diff --git a/src/Enum.php b/src/Enum.php index cfb4bd8..ca6aef0 100644 --- a/src/Enum.php +++ b/src/Enum.php @@ -28,6 +28,13 @@ abstract class Enum implements \JsonSerializable */ protected $value; + /** + * Enum key, the constant name + * + * @var string + */ + private $key; + /** * Store existing constants in a static cache per object. * @@ -61,7 +68,7 @@ public function __construct($value) $value = $value->getValue(); } - static::assertValidValue($value); + $this->key = static::assertValidValue($value); /** @psalm-var T */ $this->value = $value; @@ -94,9 +101,9 @@ public function getValue() * * @psalm-pure */ - public function getKey(): string + public function getKey() { - return static::search($this->value); + return $this->key ?? ($this->key = static::search($this->value)); } /** @@ -198,11 +205,13 @@ public static function isValid($value) * @psalm-pure * @psalm-assert T $value */ - private static function assertValidValue($value): void + private static function assertValidValue($value): string { - if (!static::isValid($value)) { + if (false === ($key = static::search($value))) { throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class); } + + return $key; } /** diff --git a/tests/EnumTest.php b/tests/EnumTest.php index e8dce2e..f1d18ac 100755 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -324,7 +324,8 @@ public function testSerialize() { // split string for Pretty CI: "Line exceeds 120 characters" $bin = '4f3a33303a224d79434c6162735c54657374735c456e756d5c456e756d4669787'. - '4757265223a313a7b733a383a22002a0076616c7565223b733a333a22666f6f223b7d'; + '4757265223a323a7b733a383a22002a0076616c7565223b733a333a22666f6f223b73'. + '3a32323a22004d79434c6162735c456e756d5c456e756d006b6579223b733a333a22464f4f223b7d'; $this->assertEquals($bin, bin2hex(serialize(EnumFixture::FOO()))); }