Skip to content

Commit

Permalink
do an array_search instead of an in_array at construct and save the k…
Browse files Browse the repository at this point in the history
…ey found so that getKey will not require an extra array search
  • Loading branch information
drealecs committed Feb 10, 2021
1 parent 34247d1 commit 60b7c4e
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 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
*/
protected $key;

/**
* Store existing constants in a static cache per object.
*
Expand Down Expand Up @@ -61,12 +68,13 @@ public function __construct($value)
$value = $value->getValue();
}

if (!$this->isValid($value)) {
if (false === ($key = static::search($value))) {
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class);
}

/** @psalm-var T */
$this->value = $value;
$this->key = $key;
}

/**
Expand All @@ -86,7 +94,7 @@ public function getValue()
*/
public function getKey(): string
{
return static::search($this->value);
return $this->key;
}

/**
Expand Down

0 comments on commit 60b7c4e

Please sign in to comment.