Skip to content

Commit

Permalink
Support UPPER_SNAKE_CASE and PascalCase in stringOptions() (resolve #22)
Browse files Browse the repository at this point in the history
  • Loading branch information
stancl committed Jan 28, 2024
1 parent fc428d5 commit fea911e
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,20 @@ public static function stringOptions(Closure $callback = null, string $glue = '\
}

// Default callback
$callback ??= fn ($name, $value) => "<option value=\"{$value}\">" . ucfirst(strtolower($name)) . '</option>';
$callback ??= function ($name, $value) {
if (str_contains($name, '_')) {
// Snake case
$words = explode('_', $name);
} else if (strtoupper($name) === $name) {
// If the entire name is uppercase without underscores, it's a single word
$words = [$name];
} else {
// Pascal case or camel case
$words = array_filter(preg_split('/(?=[A-Z])/', $name));
}

return "<option value=\"{$value}\">" . ucfirst(strtolower(implode(' ', $words))) . '</option>';
};

$options = array_map($callback, array_keys($options), array_values($options));

Expand Down
32 changes: 32 additions & 0 deletions tests/Pest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,35 @@ enum Role
#[Instructions('Guest users can only view the existing records')]
case GUEST;
}

enum MultiWordSnakeCaseEnum
{
use Options;

case FOO_BAR;
case BAR_BAZ;
}

enum BackedMultiWordSnakeCaseEnum: int
{
use Options;

case FOO_BAR = 0;
case BAR_BAZ = 1;
}

enum PascalCaseEnum
{
use Options;

case FooBar;
case BarBaz;
}

enum BackedPascalCaseEnum: int
{
use Options;

case FooBar = 0;
case BarBaz = 1;
}
13 changes: 13 additions & 0 deletions tests/Pest/OptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,16 @@
it('returns default HTML options from pure enums')
->expect(Role::stringOptions())
->toBe('<option value="ADMIN">Admin</option>\n<option value="GUEST">Guest</option>');

it('returns default HTML options from pure enums with snake case')
->expect(MultiWordSnakeCaseEnum::stringOptions())
->toBe('<option value="FOO_BAR">Foo bar</option>\n<option value="BAR_BAZ">Bar baz</option>');

it('returns default HTML options from backed enums with snake case')
->expect(BackedMultiWordSnakeCaseEnum::stringOptions())
->toBe('<option value="0">Foo bar</option>\n<option value="1">Bar baz</option>');

it('returns default HTML options from pure enums with pascal case')
->expect(BackedPascalCaseEnum::stringOptions())
->toBe('<option value="0">Foo bar</option>\n<option value="1">Bar baz</option>');

0 comments on commit fea911e

Please sign in to comment.