diff --git a/README.MD b/README.MD index 7d40f6c..dcdfa88 100644 --- a/README.MD +++ b/README.MD @@ -62,6 +62,7 @@ As you can see, values here `1`, `2`, `3`, `4`, `5`. LevelTypes::values(); // Collection: [1, 2, 3, 4, 5] LevelTypes::valuesToArray(); // Array: [1, 2, 3, 4, 5] LevelTypes::valuesToString(); // String: 1, 2, 3, 4, 5 +LevelTypes::valueOf('very easy'); // 1 ``` ### Randomize diff --git a/src/EnumValues.php b/src/EnumValues.php index 437febd..7149681 100644 --- a/src/EnumValues.php +++ b/src/EnumValues.php @@ -3,6 +3,7 @@ namespace Lazerg\LaravelEnumPro; use Illuminate\Support\Collection; +use Illuminate\Support\Str; trait EnumValues { @@ -36,4 +37,23 @@ public static function valuesToArray(): array { return self::values()->toArray(); } + + /** + * Return value of enum by name + * + * @param string $name + * @return int|string|null + */ + public static function valueOf(string $name): null|int|string + { + $name = Str::replace(' ', '_', Str::upper($name)); + + foreach (self::cases() as $case) { + if ($case->name === $name) { + return $case->value; + } + } + + return null; + } } diff --git a/tests/EnumValuesTest.php b/tests/EnumValuesTest.php index 97d4d7d..06e5b86 100644 --- a/tests/EnumValuesTest.php +++ b/tests/EnumValuesTest.php @@ -13,4 +13,18 @@ test('Get values of enum as array', function () { expect(LevelTypes::valuesToArray()) ->toBe([1, 2, 3, 4, 5]); +}); + +test('Get value of enum', function () { + expect(LevelTypes::valueOf('VERY_EASY')) + ->toBe(1); + + expect(LevelTypes::valueOf('medium')) + ->toBe(3); + + expect(LevelTypes::valueOf('Very strong')) + ->toBe(5); + + expect(LevelTypes::valueOf('Not found')) + ->toBeNull(); }); \ No newline at end of file