Skip to content

Commit 60b7c4e

Browse files
committed
do an array_search instead of an in_array at construct and save the key found so that getKey will not require an extra array search
1 parent 34247d1 commit 60b7c4e

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/Enum.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff 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+
protected $key;
37+
3138
/**
3239
* Store existing constants in a static cache per object.
3340
*
@@ -61,12 +68,13 @@ public function __construct($value)
6168
$value = $value->getValue();
6269
}
6370

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

6875
/** @psalm-var T */
6976
$this->value = $value;
77+
$this->key = $key;
7078
}
7179

7280
/**
@@ -86,7 +94,7 @@ public function getValue()
8694
*/
8795
public function getKey(): string
8896
{
89-
return static::search($this->value);
97+
return $this->key;
9098
}
9199

92100
/**

0 commit comments

Comments
 (0)