1
0
Fork 0
mirror of https://github.com/archtechx/enums.git synced 2025-12-13 08:04: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);
}
}