Skip to content

Commit

Permalink
[Feature] Get ENUM value by name (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
itsmirik authored Aug 31, 2023
1 parent eed28df commit dac62f9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions src/EnumValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Lazerg\LaravelEnumPro;

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

trait EnumValues
{
Expand Down Expand Up @@ -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;
}
}
14 changes: 14 additions & 0 deletions tests/EnumValuesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

0 comments on commit dac62f9

Please sign in to comment.