Skip to content

Commit

Permalink
cache the key value at construct changing from in_array to array_search
Browse files Browse the repository at this point in the history
  • Loading branch information
drealecs committed Feb 14, 2021
1 parent bbd35d0 commit a0076be
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
19 changes: 14 additions & 5 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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));
}

/**
Expand Down Expand Up @@ -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;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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())));
}
Expand Down

0 comments on commit a0076be

Please sign in to comment.