Skip to content

Commit

Permalink
Add stringOptions() method to the Options trait (resolve #12)
Browse files Browse the repository at this point in the history
  • Loading branch information
stancl committed Jan 12, 2024
1 parent f8438b0 commit 6684067
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
namespace ArchTech\Enums;

use BackedEnum;
use Closure;

trait Options
{
/** Get an associative array of [case name => case value]. */
/** Get an associative array of [case name => case value] or an indexed array [case name, case name] in the case of pure enums. */
public static function options(): array
{
$cases = static::cases();
Expand All @@ -17,4 +18,33 @@ public static function options(): array
? array_column($cases, 'value', 'name')
: array_column($cases, 'name');
}

/**
* Generate a string format of the enum options using the provided callback and glue.
* @param Closure(string $name, mixed $value): string $callback
*/
public static function stringOptions(Closure $callback = null, string $glue = '\n'): string
{
$firstCase = static::cases()[0] ?? null;

if ($firstCase === null) {
return '';
} elseif ($firstCase instanceof BackedEnum) {
// [name => value]
$options = static::options();
} else {
// [name, name]
$options = static::options();

// [name => name, name => name]
$options = array_combine($options, $options);
}

// Default callback
$callback ??= fn ($name, $value) => "<option value=\"{$value}\">" . ucfirst(strtolower($name)) . '</option>';

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

return implode($glue, $options);
}
}
16 changes: 16 additions & 0 deletions tests/Pest/OptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,19 @@
0 => 'ADMIN',
1 => 'GUEST',
]);

it('can return a string of options from a backed enum')
->expect(Status::stringOptions(fn ($name, $value) => "$name => $value", ', '))
->toBe("PENDING => 0, DONE => 1");

it('can return a string of options from a pure enum')
->expect(Role::stringOptions(fn ($name, $value) => "$name => $value", ', '))
->toBe("ADMIN => ADMIN, GUEST => GUEST");

it('returns default HTML options from backed enums')
->expect(Status::stringOptions())
->toBe('<option value="0">Pending</option>\n<option value="1">Done</option>');

it('returns default HTML options from pure enums')
->expect(Role::stringOptions())
->toBe('<option value="ADMIN">Admin</option>\n<option value="GUEST">Guest</option>');

0 comments on commit 6684067

Please sign in to comment.