File size: 1,846 Bytes
5f32fbd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <?php
declare(strict_types=1);
namespace App\Enums\Traits;
use App\Enums\Contracts\WithIntBackedEnum;
use App\Enums\Contracts\WithStringBackedEnum;
use Illuminate\Support\Arr;
use Illuminate\View\ComponentAttributeBag;
use UnitEnum;
trait EnumTo
{
public static function toArray(): array
{
return array_column(static::cases(), 'value');
}
public static function toOptions(string|int|WithIntBackedEnum|WithStringBackedEnum $selectedValue = '@none@', array $attributes = [], string $separator = PHP_EOL): string
{
if ($selectedValue instanceof UnitEnum) {
$selectedValue = $selectedValue->value;
}
return collect(self::cases())->map(function ($enum) use ($attributes, $selectedValue) {
$defaultAttrs = [
'value' => $enum->value,
];
if ($selectedValue !== '@none@' && $enum->value === $selectedValue) {
$defaultAttrs['selected'] = true;
}
$processedAttributes = self::processAttributes($attributes, $enum);
return sprintf(
'<option %s>%s</option>',
self::buildAttributes($defaultAttrs, $processedAttributes),
$enum->label()
);
})->implode($separator);
}
private static function processAttributes(array $attributes, $enum): array
{
return Arr::map($attributes, static function ($value, $key) use ($enum) {
return str_replace(
['%value%', '%label%'],
[$enum->value, $enum->label()],
$value
);
});
}
private static function buildAttributes(array $defaultAttrs, array $attributes): ComponentAttributeBag
{
return (new ComponentAttributeBag($defaultAttrs))->merge($attributes);
}
}
|