Files
crewli/api/app/Services/FormBuilder/FormFieldOptionService.php
bert.hausmans 11588623c5 feat(form-field): add form_field_options table, service, scope, cascade
Fourth and final WS-5 sibling. Polymorphic morph-owned table for the
RADIO / SELECT / MULTISELECT / CHECKBOX_LIST option rows, shared
between form_fields and form_field_library via the owner_type
discriminator. Matches the WS-5a (bindings) / WS-5b (validation_rules
+ configs) pattern one-for-one: dedicated service as single writer,
UNION-over-two-owner-chains scope, shared cascade observer.

Row shape:
  - value         canonical storage value (string ≤255, UNIQUE per owner)
  - label         default-locale display label (string ≤255)
  - sort_order    int unsigned
  - translations  JSON { "<locale>": "<translated label>" }

The UNIQUE(owner_type, owner_id, value) index ffo_owner_value_unique
is the seed-bug guard — duplicate values per field have no semantic
meaning and must fail at both the service layer (assertSpecsValid)
and the DB level.

Activity log: field.options_replaced emits on FormField subject only,
per the §6.7 WS-5a / §17.4.2 WS-5b convention that library-level
changes are silent in activity log.

No production reads yet. The form_fields.options and
form_field_library.options JSON columns remain the active source of
truth until the commit-3 reader switch — accessing $field->options
still resolves through the JSON cast in commit 1, so model tests
exercise the new morphMany via $field->options() (explicit relation
call). Both FormField and FormFieldLibrary now carry an `options`
morphMany alongside `bindings`, `validation_rules`, and `configs`.

Cascade: FormFieldChildTablesCascadeObserver gains form_field_options
as the fourth child cleaned on owner delete (both FormField soft/
force-delete and FormFieldLibrary delete).

Migration step-count tests in WS-5a/b/c bumped by 1 to account for
the new create_form_field_options_table on the migration stack.

Base scope-class extraction across the four siblings — deliberately
deferred to a follow-up work package per addendum §17.4.3 / §17.5.3.
Now that all four concrete implementations exist, the "what actually
varies" question can be answered empirically.

Tests: 1158 → 1182 green (+24 tests / +42 assertions).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 02:07:53 +02:00

247 lines
9.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\FormBuilder;
use App\Exceptions\FormBuilder\InvalidOptionSpecException;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormFieldOption;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Owns all writes to `form_field_options`. Single source of truth for:
*
* - row-shape enforcement (value/label/sort_order/translations)
* - duplicate-value detection at the spec level (cleaner 422 than the
* bare DB unique-constraint violation)
* - library → field row-copy on insertFromLibrary (addendum Q3
* row-copy mandate)
* - serialisation into the rich-shape JSON consumed by snapshot
* writer, API resources, and FilterRegistryController
*
* Pattern: one row per (owner, value). An empty specs array on
* `replaceOptions()` clears all option rows for the owner.
*
* Activity log convention — matches WS-5a / §17.4.2 / §17.5: emit
* `field.options_replaced` on the parent `FormField` only, not on
* `FormFieldLibrary`. Library-level audits live elsewhere.
*
* See ARCH-FORM-BUILDER §17.6 (WS-5d) for the broader rationale.
*/
final class FormFieldOptionService
{
/**
* Locale shape: BCP-47 short form — `nl`, `en`, `nl_BE`, `en_GB`.
*/
private const LOCALE_PATTERN = '/^[a-z]{2}(_[A-Z]{2})?$/';
/**
* Eager, ordered by `sort_order`. Scope-aware via the active
* organisation context.
*
* @return Collection<int, FormFieldOption>
*/
public function optionsFor(FormField|FormFieldLibrary $owner): Collection
{
$type = $this->ownerTypeFor($owner);
return FormFieldOption::query()
->where('owner_type', $type)
->where('owner_id', $owner->getKey())
->orderBy('sort_order')
->get();
}
/**
* Replace the full option set on an owner transactionally. Validates
* every spec's shape (value / label / sort_order / translations /
* uniqueness) before any write lands.
*
* @param list<array{value:string,label:string,sort_order:int,translations?:array<string,string>}> $specs
* @return Collection<int, FormFieldOption>
*/
public function replaceOptions(FormField|FormFieldLibrary $owner, array $specs): Collection
{
$this->assertSpecsValid($specs);
$ownerType = $this->ownerTypeFor($owner);
return DB::transaction(function () use ($owner, $ownerType, $specs): Collection {
FormFieldOption::query()
->withoutGlobalScopes()
->where('owner_type', $ownerType)
->where('owner_id', $owner->getKey())
->delete();
foreach ($specs as $spec) {
FormFieldOption::query()->withoutGlobalScopes()->create([
'owner_type' => $ownerType,
'owner_id' => $owner->getKey(),
'value' => $spec['value'],
'label' => $spec['label'],
'sort_order' => $spec['sort_order'],
'translations' => $this->normaliseTranslations($spec['translations'] ?? null),
]);
}
$fresh = $this->optionsFor($owner);
if ($owner instanceof FormField) {
$owner->logFieldChange('field.options_replaced', [
'options' => $this->toJsonShape($fresh),
]);
}
return $fresh;
});
}
/**
* Row-copy from a library entry to a freshly-inserted field
* (addendum Q3 row-copy mandate). Every column is preserved; only
* `owner_type` / `owner_id` change. No activity-log emit — the
* wrapping library-insert emits its own field-creation event.
*
* @return Collection<int, FormFieldOption>
*/
public function copyOptions(FormFieldLibrary|FormField $from, FormField|FormFieldLibrary $to): Collection
{
$rows = $this->optionsFor($from);
if ($rows->isEmpty()) {
return $rows;
}
$toType = $this->ownerTypeFor($to);
return DB::transaction(function () use ($rows, $to, $toType): Collection {
foreach ($rows as $row) {
FormFieldOption::query()->withoutGlobalScopes()->create([
'owner_type' => $toType,
'owner_id' => $to->getKey(),
'value' => $row->value,
'label' => $row->label,
'sort_order' => $row->sort_order,
'translations' => is_array($row->translations) && $row->translations !== []
? $row->translations
: null,
]);
}
return $this->optionsFor($to);
});
}
/**
* Serialise an option collection into the rich-shape array consumed
* by snapshot writer, API resources, and FilterRegistryController.
* Returns the mapped list (possibly empty); callers handle
* empty-collection → `null` emit at the resource boundary.
*
* @param Collection<int, FormFieldOption> $options
* @return list<array{value:string,label:string,sort_order:int,translations?:array<string,string>}>
*/
public function toJsonShape(Collection $options): array
{
return $options
->sortBy('sort_order')
->values()
->map(fn (FormFieldOption $option) => $option->toJsonShape())
->all();
}
/**
* Public spec-shape gate — used by FormRequests (WS-5d commit 3) to
* reject malformed specs at the HTTP boundary before any write
* lands.
*
* @param list<array<string, mixed>> $specs
*/
public function assertSpecsValid(array $specs): void
{
$seenValues = [];
foreach ($specs as $index => $spec) {
if (! is_array($spec)) {
throw new InvalidOptionSpecException(
"Option spec at index {$index} must be an array.",
);
}
$value = $spec['value'] ?? null;
if (! is_string($value) || $value === '' || strlen($value) > 255) {
throw new InvalidOptionSpecException(
"Option spec at index {$index}: 'value' is required, must be a non-empty string ≤255 chars.",
);
}
$label = $spec['label'] ?? null;
if (! is_string($label) || $label === '' || strlen($label) > 255) {
throw new InvalidOptionSpecException(
"Option spec at index {$index}: 'label' is required, must be a non-empty string ≤255 chars.",
);
}
if (! array_key_exists('sort_order', $spec)
|| ! is_int($spec['sort_order'])
|| $spec['sort_order'] < 0) {
throw new InvalidOptionSpecException(
"Option spec at index {$index}: 'sort_order' is required, must be a non-negative integer.",
);
}
if (array_key_exists('translations', $spec) && $spec['translations'] !== null) {
$translations = $spec['translations'];
if (! is_array($translations)) {
throw new InvalidOptionSpecException(
"Option spec at index {$index}: 'translations' must be an associative array of locale ⇒ string.",
);
}
foreach ($translations as $locale => $translated) {
if (! is_string($locale) || preg_match(self::LOCALE_PATTERN, $locale) !== 1) {
throw new InvalidOptionSpecException(
"Option spec at index {$index}: invalid locale key '{$locale}' (expected BCP-47 short form e.g. 'nl', 'en_GB').",
);
}
if (! is_string($translated) || $translated === '' || strlen($translated) > 255) {
throw new InvalidOptionSpecException(
"Option spec at index {$index} locale '{$locale}': translated label must be a non-empty string ≤255 chars.",
);
}
}
}
if (in_array($value, $seenValues, true)) {
throw new InvalidOptionSpecException(
"Option spec at index {$index}: duplicate value '{$value}' within the spec list.",
);
}
$seenValues[] = $value;
}
}
private function ownerTypeFor(FormField|FormFieldLibrary $owner): string
{
return $owner instanceof FormField ? 'form_field' : 'form_field_library';
}
/**
* Empty translation bags are stored as NULL — keeps query semantics
* clean and avoids whitespace differences between equivalent rows.
*
* @param array<string, string>|null $translations
* @return array<string, string>|null
*/
private function normaliseTranslations(?array $translations): ?array
{
if ($translations === null || $translations === []) {
return null;
}
return $translations;
}
}