1
0
Fork 0
mirror of https://github.com/archtechx/enums.git synced 2025-12-12 05:24:03 +00:00

Add stringOptions() method to the Options trait (resolve #12)

This commit is contained in:
Samuel Štancl 2024-01-12 23:11:09 +01:00
parent f8438b0313
commit 6684067b9e
2 changed files with 47 additions and 1 deletions

View file

@ -5,10 +5,11 @@ declare(strict_types=1);
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();
@ -17,4 +18,33 @@ trait Options
? 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);
}
}

View file

@ -11,3 +11,19 @@ it('can return an indexed array of options from a pure enum')
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>');