feat(form-builder): form_field_bindings table + polymorphic owner + cascade observer

WS-5a commit 1 of 4 per ARCH-CONSOLIDATION-ADDENDUM-2026-04-24 Q3.

Creates the relational home for what was form_fields.binding JSON and
form_field_library.default_binding JSON. Owner discriminator is polymorphic
morph (owner_type/owner_id) — the pattern the rest of WS-5 (5b validation_rules,
5d options) will reuse.

Migration backfills rows from both JSON sources in a single transaction and
is genuinely reversible (rollback reconstructs the JSON). Old columns remain
in place until commit 3 has switched all readers.

Pattern B (binding=null) is represented by absence of row. mode enum covers
entity_owned / mirrored only.

Cascade on owner delete via observer — bindings are physical state, not
historical audit. FormFieldBindingScope enforces multi-tenancy via UNION over
both owner chains (form_field → schema → org OR form_field_library → org) —
Q2's declarative tenantScopeStrategy() can't walk morph parents.

Tests: migration forward/back, morph relation, cascade observer, scope
isolation, enum coverage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-24 18:43:11 +02:00
parent 76090b934e
commit af8a9da038
17 changed files with 1081 additions and 0 deletions

View File

@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\Bindings;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldBinding;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class FormFieldBindingCascadeTest extends TestCase
{
use RefreshDatabase;
public function test_soft_delete_of_field_cascades_bindings(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
FormFieldBinding::factory()->forField($field)->entityOwned('person', 'email')->create();
FormFieldBinding::factory()->forField($field)->mirrored('user_profile', 'bio')->create();
$this->assertSame(2, FormFieldBinding::query()
->withoutGlobalScopes()
->where('owner_type', 'form_field')
->where('owner_id', $field->id)
->count(),
);
$field->delete(); // soft delete on FormField
$this->assertSame(0, FormFieldBinding::query()
->withoutGlobalScopes()
->where('owner_type', 'form_field')
->where('owner_id', $field->id)
->count(),
);
}
public function test_delete_of_library_entry_cascades_bindings(): void
{
$org = Organisation::factory()->create();
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
FormFieldBinding::factory()->forLibrary($library)->entityOwned('person', 'first_name')->create();
$this->assertSame(1, FormFieldBinding::query()
->withoutGlobalScopes()
->where('owner_type', 'form_field_library')
->where('owner_id', $library->id)
->count(),
);
$library->delete();
$this->assertSame(0, FormFieldBinding::query()
->withoutGlobalScopes()
->where('owner_type', 'form_field_library')
->where('owner_id', $library->id)
->count(),
);
}
public function test_deleting_one_field_does_not_cascade_others(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$a = FormField::factory()->create(['form_schema_id' => $schema->id]);
$b = FormField::factory()->create(['form_schema_id' => $schema->id]);
FormFieldBinding::factory()->forField($a)->entityOwned('person', 'email')->create();
FormFieldBinding::factory()->forField($b)->entityOwned('person', 'phone')->create();
$a->delete();
$this->assertSame(1, FormFieldBinding::query()
->withoutGlobalScopes()
->where('owner_type', 'form_field')
->where('owner_id', $b->id)
->count(),
);
}
}

View File

@@ -0,0 +1,243 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\Bindings;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Tests\TestCase;
/**
* Seeds pre-migration JSON into `form_fields.binding` and
* `form_field_library.default_binding`, then runs the migration forward
* and back asserting both directions.
*
* Forward: rows land in `form_field_bindings` with the correct
* owner_type/owner_id + translated columns. Backward: JSON is
* reconstructed into the source tables, table dropped.
*/
final class FormFieldBindingMigrationTest extends TestCase
{
use RefreshDatabase;
private const MIGRATION_PATH = 'database/migrations/2026_04_25_100000_create_form_field_bindings_table.php';
public function test_forward_migration_backfills_rows_from_both_json_sources(): void
{
// Start from a clean slate where form_field_bindings does not exist.
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
$this->assertFalse(Schema::hasTable('form_field_bindings'));
[$fieldAId, $fieldCId, $fieldDId] = $this->seedFieldsWithBindingJson();
[$libAId, $libCId] = $this->seedLibraryWithBindingJson();
$this->artisan('migrate', [
'--path' => self::MIGRATION_PATH,
'--realpath' => false,
])->assertSuccessful();
$this->assertTrue(Schema::hasTable('form_field_bindings'));
$rows = DB::table('form_field_bindings')->orderBy('owner_type')->orderBy('owner_id')->get();
$this->assertCount(5, $rows, 'Expected 3 field + 2 library rows');
$fieldRowA = DB::table('form_field_bindings')
->where('owner_type', 'form_field')
->where('owner_id', $fieldAId)
->first();
$this->assertNotNull($fieldRowA);
$this->assertSame('person', $fieldRowA->target_entity);
$this->assertSame('email', $fieldRowA->target_attribute);
$this->assertSame('entity_owned', $fieldRowA->mode);
$this->assertNull($fieldRowA->sync_direction);
$this->assertSame('overwrite', $fieldRowA->merge_strategy);
$this->assertSame(50, (int) $fieldRowA->trust_level);
$this->assertSame(0, (int) $fieldRowA->is_identity_key);
$fieldRowC = DB::table('form_field_bindings')
->where('owner_type', 'form_field')
->where('owner_id', $fieldCId)
->first();
$this->assertNotNull($fieldRowC);
$this->assertSame('mirrored', $fieldRowC->mode);
$this->assertSame('write_on_submit', $fieldRowC->sync_direction);
$this->assertSame('user_profile', $fieldRowC->target_entity);
$this->assertSame('emergency_contact_name', $fieldRowC->target_attribute);
$fieldRowD = DB::table('form_field_bindings')
->where('owner_type', 'form_field')
->where('owner_id', $fieldDId)
->first();
$this->assertNotNull($fieldRowD);
$this->assertSame('entity_owned', $fieldRowD->mode);
$libRowA = DB::table('form_field_bindings')
->where('owner_type', 'form_field_library')
->where('owner_id', $libAId)
->first();
$this->assertNotNull($libRowA);
$this->assertSame('person', $libRowA->target_entity);
$this->assertSame('first_name', $libRowA->target_attribute);
$this->assertSame('entity_owned', $libRowA->mode);
$libRowC = DB::table('form_field_bindings')
->where('owner_type', 'form_field_library')
->where('owner_id', $libCId)
->first();
$this->assertNotNull($libRowC);
$this->assertSame('mirrored', $libRowC->mode);
}
public function test_rollback_reconstructs_json_and_drops_table(): void
{
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
[$fieldAId, , ] = $this->seedFieldsWithBindingJson();
[$libAId, ] = $this->seedLibraryWithBindingJson();
$this->artisan('migrate', [
'--path' => self::MIGRATION_PATH,
'--realpath' => false,
])->assertSuccessful();
// Wipe the source JSON to prove the rollback writes back from rows.
DB::table('form_fields')->where('id', $fieldAId)->update(['binding' => null]);
DB::table('form_field_library')->where('id', $libAId)->update(['default_binding' => null]);
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
$this->assertFalse(Schema::hasTable('form_field_bindings'));
$field = DB::table('form_fields')->where('id', $fieldAId)->first();
$this->assertNotNull($field->binding);
$json = json_decode((string) $field->binding, true);
$this->assertSame([
'mode' => 'entity_owned',
'entity' => 'person',
'column' => 'email',
], $json);
$lib = DB::table('form_field_library')->where('id', $libAId)->first();
$this->assertNotNull($lib->default_binding);
$libJson = json_decode((string) $lib->default_binding, true);
$this->assertSame([
'mode' => 'entity_owned',
'entity' => 'person',
'column' => 'first_name',
], $libJson);
}
/** @return array{0:string,1:string,2:string} */
private function seedFieldsWithBindingJson(): array
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$fieldA = (string) Str::ulid();
$fieldC = (string) Str::ulid();
$fieldD = (string) Str::ulid();
DB::table('form_fields')->insert([
[
'id' => $fieldA,
'form_schema_id' => $schema->id,
'field_type' => 'EMAIL',
'slug' => 'email',
'label' => 'E-mail',
'binding' => json_encode(['mode' => 'entity_owned', 'entity' => 'person', 'column' => 'email']),
'value_storage_hint' => 'indexed',
'sort_order' => 0,
'created_at' => now(),
'updated_at' => now(),
],
[
'id' => $fieldC,
'form_schema_id' => $schema->id,
'field_type' => 'TEXT',
'slug' => 'noodcontact',
'label' => 'Noodcontact',
'binding' => json_encode([
'mode' => 'mirrored',
'entity' => 'user_profile',
'column' => 'emergency_contact_name',
'sync_direction' => 'write_on_submit',
]),
'value_storage_hint' => 'indexed',
'sort_order' => 1,
'created_at' => now(),
'updated_at' => now(),
],
[
'id' => $fieldD,
'form_schema_id' => $schema->id,
'field_type' => 'TEXT',
'slug' => 'voornaam',
'label' => 'Voornaam',
'binding' => json_encode(['mode' => 'entity_owned', 'entity' => 'person', 'column' => 'first_name']),
'value_storage_hint' => 'indexed',
'sort_order' => 2,
'created_at' => now(),
'updated_at' => now(),
],
]);
return [$fieldA, $fieldC, $fieldD];
}
/** @return array{0:string,1:string} */
private function seedLibraryWithBindingJson(): array
{
$org = Organisation::factory()->create();
$libA = (string) Str::ulid();
$libC = (string) Str::ulid();
DB::table('form_field_library')->insert([
[
'id' => $libA,
'organisation_id' => $org->id,
'name' => 'Voornaam bibliotheek',
'slug' => 'voornaam-lib',
'field_type' => 'TEXT',
'label' => 'Voornaam',
'default_binding' => json_encode(['mode' => 'entity_owned', 'entity' => 'person', 'column' => 'first_name']),
'default_is_required' => false,
'default_is_filterable' => false,
'usage_count' => 0,
'is_system' => false,
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
[
'id' => $libC,
'organisation_id' => $org->id,
'name' => 'Noodcontact bibliotheek',
'slug' => 'noodcontact-lib',
'field_type' => 'TEXT',
'label' => 'Noodcontact',
'default_binding' => json_encode([
'mode' => 'mirrored',
'entity' => 'user_profile',
'column' => 'emergency_contact_phone',
'sync_direction' => 'write_on_submit',
]),
'default_is_required' => false,
'default_is_filterable' => false,
'usage_count' => 0,
'is_system' => false,
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
]);
return [$libA, $libC];
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\Bindings;
use App\Enums\FormBuilder\FormFieldBindingMode;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldBinding;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class FormFieldBindingRelationTest extends TestCase
{
use RefreshDatabase;
public function test_field_morph_many_bindings_loads_all(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
FormFieldBinding::factory()->forField($field)->entityOwned('person', 'email')->create();
FormFieldBinding::factory()->forField($field)->mirrored('user_profile', 'bio')->create();
$bindings = $field->fresh()->bindings;
$this->assertCount(2, $bindings);
$targets = $bindings->pluck('target_attribute')->sort()->values()->all();
$this->assertSame(['bio', 'email'], $targets);
}
public function test_library_morph_many_bindings_loads_all(): void
{
$org = Organisation::factory()->create();
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
FormFieldBinding::factory()->forLibrary($library)->entityOwned('person', 'first_name')->create();
$bindings = $library->fresh()->bindings;
$this->assertCount(1, $bindings);
$this->assertSame('first_name', $bindings->first()->target_attribute);
}
public function test_owner_morphto_returns_correct_concrete_model(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
$fieldBinding = FormFieldBinding::factory()->forField($field)->entityOwned('person', 'email')->create();
$libraryBinding = FormFieldBinding::factory()->forLibrary($library)->entityOwned('person', 'phone')->create();
$this->assertInstanceOf(FormField::class, $fieldBinding->fresh()->owner);
$this->assertSame($field->id, $fieldBinding->fresh()->owner->id);
$this->assertInstanceOf(FormFieldLibrary::class, $libraryBinding->fresh()->owner);
$this->assertSame($library->id, $libraryBinding->fresh()->owner->id);
}
public function test_mode_and_merge_strategy_cast_to_enums(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
$binding = FormFieldBinding::factory()->forField($field)->mirrored('person', 'email')->create();
$fresh = $binding->fresh();
$this->assertSame(FormFieldBindingMode::Mirrored, $fresh->mode);
$this->assertTrue($fresh->isMirrored());
$this->assertFalse($fresh->isEntityOwned());
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\Bindings;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldBinding;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use App\Models\Scopes\FormFieldBindingScope;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Routing\Route;
use Tests\TestCase;
/**
* Asserts `FormFieldBindingScope` isolates bindings per organisation across
* both owner types (form_field and form_field_library) and that the
* withoutGlobalScope escape hatch exposes cross-org rows.
*/
final class FormFieldBindingScopeTest extends TestCase
{
use RefreshDatabase;
public function test_scope_isolates_bindings_per_organisation_for_both_owner_types(): void
{
[$orgA, $fieldA, $libraryA] = $this->seedOrgWithBindings();
[$orgB, $fieldB, $libraryB] = $this->seedOrgWithBindings();
$this->withOrgRoute($orgA);
$ownerIdsA = FormFieldBinding::query()->pluck('owner_id')->sort()->values()->all();
$expectedA = collect([$fieldA->id, $libraryA->id])->sort()->values()->all();
$this->assertSame($expectedA, $ownerIdsA);
$this->withOrgRoute($orgB);
$ownerIdsB = FormFieldBinding::query()->pluck('owner_id')->sort()->values()->all();
$expectedB = collect([$fieldB->id, $libraryB->id])->sort()->values()->all();
$this->assertSame($expectedB, $ownerIdsB);
}
public function test_without_global_scope_exposes_cross_org(): void
{
[$orgA, , ] = $this->seedOrgWithBindings();
$this->seedOrgWithBindings();
$this->withOrgRoute($orgA);
$this->assertSame(
4,
FormFieldBinding::query()->withoutGlobalScope(FormFieldBindingScope::class)->count(),
);
$this->assertSame(2, FormFieldBinding::query()->count());
}
/** @return array{0:Organisation,1:FormField,2:FormFieldLibrary} */
private function seedOrgWithBindings(): array
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
FormFieldBinding::factory()->forField($field)->entityOwned('person', 'email')->create();
FormFieldBinding::factory()->forLibrary($library)->entityOwned('person', 'first_name')->create();
return [$org, $field, $library];
}
private function withOrgRoute(Organisation $org): void
{
$route = new Route(['GET'], '/_test', static fn () => null);
$route->bind(request());
$route->setParameter('organisation', $org);
request()->setRouteResolver(static fn () => $route);
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Enums\FormBuilder;
use App\Enums\FormBuilder\FormFieldBindingMergeStrategy;
use App\Enums\FormBuilder\FormFieldBindingMode;
use PHPUnit\Framework\TestCase;
final class FormFieldBindingEnumsTest extends TestCase
{
public function test_mode_has_expected_cases(): void
{
$values = array_map(fn ($case) => $case->value, FormFieldBindingMode::cases());
$this->assertSame(['entity_owned', 'mirrored'], $values);
}
public function test_mode_from_string(): void
{
$this->assertSame(FormFieldBindingMode::EntityOwned, FormFieldBindingMode::from('entity_owned'));
$this->assertSame(FormFieldBindingMode::Mirrored, FormFieldBindingMode::from('mirrored'));
}
public function test_mode_rejects_legacy_form_owned(): void
{
$this->expectException(\ValueError::class);
FormFieldBindingMode::from('form_owned');
}
public function test_merge_strategy_has_expected_cases(): void
{
$values = array_map(fn ($case) => $case->value, FormFieldBindingMergeStrategy::cases());
sort($values);
$this->assertSame(['append', 'first_write_wins', 'overwrite', 'replace'], $values);
}
public function test_merge_strategy_from_string(): void
{
$this->assertSame(
FormFieldBindingMergeStrategy::Overwrite,
FormFieldBindingMergeStrategy::from('overwrite'),
);
$this->assertSame(
FormFieldBindingMergeStrategy::FirstWriteWins,
FormFieldBindingMergeStrategy::from('first_write_wins'),
);
}
}