Files
crewli/api/app/Http/Resources/FormBuilder/FormFieldResource.php
bert.hausmans bb9242fd6e refactor(form-field): resources + snapshot + validator read form_field_options
Atomic reader switch. All call paths that previously read
form_fields.options / form_field_library.options from the JSON column
now read through FormFieldOptionService::toJsonShape() via the
morphMany relation:

  - FormFieldResource + FormFieldLibraryResource +
    PublicFormSchemaResource emit the rich-shape array
  - FilterRegistryController emits rich shape uniformly (no flat-array
    carve-out for filter-UI compatibility — preflight scan confirmed
    zero portal/app consumers, S5 territory)
  - FormFieldRuleBuilder plucks values from the relation for in:options
    rule construction
  - FormSubmissionService::buildSnapshot writes rich-shape options into
    snapshots and strips translations.{locale}.options from each field's
    translations bag (defensive — commit 2 backfill already did the
    bulk strip)
  - Four FormFieldRequest variants accept array-of-spec-objects,
    validate shape in after() via FormFieldOptionService::assertSpecsValid,
    and hand off to FormFieldOptionService::replaceOptions for writes
  - FormFieldService::create + update extract option specs from the
    request data and route through the service after the FormField row
    is persisted

FormField and FormFieldLibrary $casts no longer include 'options'; the
JSON column is no longer cast. Options removed from $fillable on both
models so ::create() / ::fill() / mass assignment can no longer touch
the legacy column. Both models gain a getOptionsAttribute() accessor
that resolves $model->options to the eager-loaded morphMany collection
— required because Eloquent's getAttribute() prefers a real DB column
over a relation method, and the JSON column lives on the table until
WS-5d commit 5 drops it.

Activity log — dual emit per §6.7 / §17.4.2 / §17.6.3:
  - field.updated carries old.options / new.options diff via
    toJsonShape() reconstruction, byte-equal JSON compare to avoid
    cosmetic false positives. Field updates that don't touch options
    omit the key entirely
  - field.options_replaced emits inside replaceOptions() on FormField
    subject only; library subject writes silent (mirrors the WS-5b /
    WS-5c convention)

JSON columns (form_fields.options, form_field_library.options) remain
present but unread — column drops land atomically in commit 5.

Two pre-existing test fixtures that seeded options via the JSON column
(FormFieldApiTest + PublicFormValidationTest) migrated to the
spec-array path: FormField::factory()->withOptions([...]) where the
options live on the field, or explicit spec-array request bodies for
HTTP tests.

Tests: 1193 → 1206 green (+13 tests / +28 assertions).

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

129 lines
4.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Resources\FormBuilder;
use App\Enums\FormBuilder\FormFieldType;
use App\Models\FormBuilder\FormField;
use App\Models\PersonTag;
use App\Services\FormBuilder\FormFieldBindingService;
use App\Services\FormBuilder\FormFieldConditionalLogicService;
use App\Services\FormBuilder\FormFieldConfigService;
use App\Services\FormBuilder\FormFieldOptionService;
use App\Services\FormBuilder\FormFieldValidationRuleService;
use App\Services\FormBuilder\FormLocaleResolver;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin FormField
*/
final class FormFieldResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$locale = app(FormLocaleResolver::class)->resolve(
$this->resource->schema,
$request->user(),
);
$this->resource->loadMissing('options');
return [
'id' => $this->id,
'form_schema_id' => $this->form_schema_id,
'form_schema_section_id' => $this->form_schema_section_id,
'library_field_id' => $this->library_field_id,
'field_type' => $this->field_type,
'slug' => $this->slug,
'label' => $this->resolvedLabel($locale),
'help_text' => $this->resolvedHelpText($locale),
'section' => $this->section,
'options' => $this->resource->options->isNotEmpty()
? app(FormFieldOptionService::class)->toJsonShape($this->resource->options)
: null,
'available_tags' => $this->when(
$this->field_type === FormFieldType::TAG_PICKER->value,
fn () => $this->availableTags(),
),
'validation_rules' => app(FormFieldValidationRuleService::class)->toJsonShape(
$this->resource->validationRules,
),
'configs' => app(FormFieldConfigService::class)->toJsonShape(
$this->resource->configs,
),
'is_required' => (bool) $this->is_required,
'is_filterable' => (bool) $this->is_filterable,
'is_portal_visible' => (bool) $this->is_portal_visible,
'is_admin_only' => (bool) $this->is_admin_only,
'is_unique' => (bool) $this->is_unique,
'is_pii' => (bool) $this->is_pii,
'display_width' => $this->display_width instanceof \BackedEnum ? $this->display_width->value : $this->display_width,
'binding' => app(FormFieldBindingService::class)->toJsonShape(
$this->resource->bindings->first(),
),
'conditional_logic' => app(FormFieldConditionalLogicService::class)->toJsonShape(
$this->resource->rootConditionalLogicGroup(),
),
'role_restrictions' => $this->role_restrictions,
'translations' => $this->translations,
'value_storage_hint' => $this->value_storage_hint instanceof \BackedEnum ? $this->value_storage_hint->value : $this->value_storage_hint,
'review_required' => (bool) $this->review_required,
'sort_order' => (int) $this->sort_order,
];
}
private function resolvedLabel(string $locale): string
{
$translations = $this->translations ?? [];
if (isset($translations[$locale]['label']) && $translations[$locale]['label'] !== '') {
return (string) $translations[$locale]['label'];
}
return (string) $this->label;
}
private function resolvedHelpText(string $locale): ?string
{
$translations = $this->translations ?? [];
if (isset($translations[$locale]['help_text'])) {
return (string) $translations[$locale]['help_text'];
}
return $this->help_text;
}
/**
* @return array<int, array<string, string>>
*/
private function availableTags(): array
{
$organisationId = $this->resource->schema?->organisation_id;
if ($organisationId === null) {
return [];
}
$configs = app(FormFieldConfigService::class)->toJsonShape($this->resource->configs);
$categoryFilter = (array) ($configs['tag_categories']['categories'] ?? []);
$query = PersonTag::withoutGlobalScopes()
->where('organisation_id', $organisationId)
->where('is_active', true);
if ($categoryFilter !== []) {
$query->whereIn('category', $categoryFilter);
}
return $query->get(['id', 'name', 'category'])
->map(fn ($t) => [
'id' => (string) $t->id,
'name' => (string) $t->name,
'category' => (string) $t->category,
])
->all();
}
}