diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..b3a390c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# [Unreleased] + +- Add Enum::instanceFromKey($key) + +# 1.1.0 + +- Add flip() and fromValue() + +# 1.0.0 + +- initial release + diff --git a/README.md b/README.md index 18e24bc..b9b963e 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,10 @@ Animal::DOG()->value(); // (null) - No value was assigned in map() Animal::PIGEON()->key(); // "skyrat" Animal::PIGEON()->value(); // (array)['you', 'filthy', 'animal'] + +// Get a new Enum instance from a given key +$kitty = 'kitty'; +$cat = Animal::instanceFromKey($kitty); ``` ## Dependencies @@ -207,6 +211,10 @@ Returns the value (or null if not mapped) for the given key (as declared in the Returns the constant for the given value (as declared in the `map()` method). > Caveats: Only works with single dimension arrays and it will only return the last key if multiple keys have the same value. +### instanceFromKey($key) + +Create instance of this Enum from the given key. + ### exists(string $key) Returns true if the given key exists. diff --git a/src/Enum.php b/src/Enum.php index cb04dbb..cf4109d 100644 --- a/src/Enum.php +++ b/src/Enum.php @@ -202,6 +202,25 @@ public static function fromValue($value) return $flipped[$value]; } + /** + * Create instance of this Enum from the key. + * + * @param string|int $key + * + * @return static + * @throws InvalidKeyException + */ + public static function instanceFromKey($key): self + { + foreach (self::constantMap() as $identifier => $validKey) { + if ($key === $validKey) { + return static::{$identifier}(); + } + } + + throw new InvalidKeyException(sprintf('Invalid key: %s in %s', $key, static::class)); + } + /** * Determine if a key exists within the constant map * diff --git a/tests/Unit/EnumTest.php b/tests/Unit/EnumTest.php index 6aa0ccb..7520c85 100644 --- a/tests/Unit/EnumTest.php +++ b/tests/Unit/EnumTest.php @@ -178,4 +178,16 @@ public function test_flipable_trait_throws_exception_with_invalid_value() $this->expectException(InvalidValueException::class); $this->assertEquals(Bevs::BREW, Bevs::fromValue('Water')); } + + public function test_get_instance_via_key() + { + $animal = Animal::instanceFromKey('kitty'); + $this->assertTrue($animal->is(Animal::CAT())); + } + + public function test_get_instance_via_invalid_key_throws_exception() + { + $this->expectException(InvalidKeyException::class); + Animal::instanceFromKey('_invalid_key_'); + } }