38 lines
1.2 KiB
PHP
38 lines
1.2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Modules\CustomField\Actions;
|
||
|
|
|
||
|
|
use App\Modules\CustomField\DTOs\CustomFieldDefinitionData;
|
||
|
|
use App\Modules\CustomField\Models\CustomFieldDefinition;
|
||
|
|
use App\Modules\CustomField\Models\CustomFieldType;
|
||
|
|
use Illuminate\Support\Str;
|
||
|
|
|
||
|
|
final class CreateCustomFieldDefinitionAction
|
||
|
|
{
|
||
|
|
public function handle(CustomFieldDefinitionData $data): CustomFieldDefinition
|
||
|
|
{
|
||
|
|
return CustomFieldDefinition::create([
|
||
|
|
'label' => $data->label,
|
||
|
|
'key' => $this->uniqueKey($data->label),
|
||
|
|
'type' => $data->type,
|
||
|
|
'options' => $data->type === CustomFieldType::Select->value ? array_values($data->options ?? []) : null,
|
||
|
|
'is_required' => $data->isRequired,
|
||
|
|
// New entries always land at the end of the list.
|
||
|
|
'sort_order' => (CustomFieldDefinition::max('sort_order') ?? -1) + 1,
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
|
||
|
|
private function uniqueKey(string $label): string
|
||
|
|
{
|
||
|
|
$base = Str::slug($label, '_') ?: 'field';
|
||
|
|
$key = $base;
|
||
|
|
$i = 1;
|
||
|
|
|
||
|
|
while (CustomFieldDefinition::withTrashed()->where('key', $key)->exists()) {
|
||
|
|
$key = $base.'_'.(++$i);
|
||
|
|
}
|
||
|
|
|
||
|
|
return $key;
|
||
|
|
}
|
||
|
|
}
|