feat(form-builder): FormFieldValidationRuleService + legacy backfill + snapshot + library row-copy

This commit is contained in:
2026-04-24 22:12:08 +02:00
parent fedaed1b32
commit 800b1b6c01
16 changed files with 1430 additions and 18 deletions

View File

@@ -33,9 +33,10 @@ final class FormFieldBindingMigrationTest extends TestCase
public function test_forward_migrations_backfill_rows_from_both_json_sources(): void
{
// Roll back: create_form_field_validation_rules_table (WS-5b commit 1)
// Roll back, newest first: backfill_form_field_validation_rules
// → create_form_field_validation_rules_table (both WS-5b commit 1+2)
// → drop_binding_json_columns → create_form_field_bindings.
$this->artisan('migrate:rollback', ['--step' => 3])->assertSuccessful();
$this->artisan('migrate:rollback', ['--step' => 4])->assertSuccessful();
$this->assertFalse(Schema::hasTable('form_field_bindings'));
$this->assertTrue(Schema::hasColumn('form_fields', 'binding'));
$this->assertTrue(Schema::hasColumn('form_field_library', 'default_binding'));
@@ -96,9 +97,10 @@ final class FormFieldBindingMigrationTest extends TestCase
public function test_rollback_reconstructs_json_and_drops_table(): void
{
// Walk back: validation-rules table (WS-5b commit 1) →
// drop_binding_json_columns → create_form_field_bindings.
$this->artisan('migrate:rollback', ['--step' => 3])->assertSuccessful();
// Walk back the full WS-5b + WS-5a stack: backfill (validation rules)
// → create (validation rules table) → drop (binding columns) →
// create (bindings table).
$this->artisan('migrate:rollback', ['--step' => 4])->assertSuccessful();
[$fieldAId, , ] = $this->seedFieldsWithBindingJson();
[$libAId, ] = $this->seedLibraryWithBindingJson();
@@ -108,9 +110,9 @@ final class FormFieldBindingMigrationTest extends TestCase
$this->assertFalse(Schema::hasColumn('form_fields', 'binding'));
$this->assertSame(5, DB::table('form_field_bindings')->count());
// Step back over WS-5b validation-rules table → irrelevant to the
// binding contract, but restores the pre-WS-5b state.
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
// Step back over the two WS-5b migrations → restores the pre-WS-5b
// state (validation-rules table gone; binding contract intact).
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
$this->assertFalse(Schema::hasTable('form_field_validation_rules'));
$this->assertTrue(Schema::hasTable('form_field_bindings'));

View File

@@ -187,7 +187,11 @@ final class PublicFormSeederTest extends TestCase
$this->assertArrayHasKey('sectie_voorkeur', $fields);
$this->assertSame(FormFieldType::SECTION_PRIORITY->value, $fields['sectie_voorkeur']['field_type']);
$this->assertSame('full', $fields['sectie_voorkeur']['display_width']);
$this->assertSame(['max_priorities' => 3], $fields['sectie_voorkeur']['validation_rules']);
// WS-5b canonicalised `max_priorities` → `max_selected` (shared
// semantic of "cap on entries in a list-valued field"). Resource
// emits the new canonical key via
// FormFieldValidationRuleService::toJsonShape().
$this->assertSame(['max_selected' => 3], $fields['sectie_voorkeur']['validation_rules']);
}
public function test_time_slots_endpoint_returns_at_least_four_volunteer_rows(): void

View File

@@ -0,0 +1,273 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\ValidationRules;
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;
/**
* Rolls back the WS-5b commit 1+2 migrations, seeds pre-WS-5b JSON, then
* runs the migrations forward and back asserting:
*
* - Forward: canonical rows land in form_field_validation_rules with
* the correct field-type dispatch for legacy `min`/`max` ambiguity
* and `max_priorities` canonicalised to `max_selected`.
* - Forward: `tag_categories` / `storage_disk` are skipped (handled by
* commit 5's configs backfill).
* - Rollback: the rows are serialised back into the JSON column using
* canonical keys. `required` / `unique` keys are not reconstructed
* (never migrated).
*/
final class FormFieldValidationRuleBackfillTest extends TestCase
{
use RefreshDatabase;
public function test_forward_migration_backfills_rows_with_field_type_dispatch(): void
{
// Roll back: backfill + create-table. Brings us to a state where
// form_fields.validation_rules exists but form_field_validation_rules
// table does not.
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
$this->assertFalse(Schema::hasTable('form_field_validation_rules'));
$this->assertTrue(Schema::hasColumn('form_fields', 'validation_rules'));
[$numberId, $textId, $dateId, $sectionPriorityId] = $this->seedFields();
[$libAId] = $this->seedLibrary();
$this->artisan('migrate')->assertSuccessful();
$this->assertTrue(Schema::hasTable('form_field_validation_rules'));
$numberRules = DB::table('form_field_validation_rules')
->where('owner_type', 'form_field')
->where('owner_id', $numberId)
->get()->keyBy('rule_type');
$this->assertTrue($numberRules->has('min_value'));
$this->assertTrue($numberRules->has('max_value'));
$this->assertSame(16, json_decode((string) $numberRules['min_value']->parameters, true)['value']);
$this->assertSame(99, json_decode((string) $numberRules['max_value']->parameters, true)['value']);
$textRules = DB::table('form_field_validation_rules')
->where('owner_type', 'form_field')
->where('owner_id', $textId)
->get()->keyBy('rule_type');
$this->assertTrue($textRules->has('min_length'));
$this->assertTrue($textRules->has('max_length'));
$this->assertSame(5, json_decode((string) $textRules['min_length']->parameters, true)['value']);
$this->assertSame(80, json_decode((string) $textRules['max_length']->parameters, true)['value']);
$dateRules = DB::table('form_field_validation_rules')
->where('owner_type', 'form_field')
->where('owner_id', $dateId)
->get()->keyBy('rule_type');
$this->assertTrue($dateRules->has('date_min'));
$this->assertSame('2026-01-01', json_decode((string) $dateRules['date_min']->parameters, true)['date']);
$sectionRules = DB::table('form_field_validation_rules')
->where('owner_type', 'form_field')
->where('owner_id', $sectionPriorityId)
->get()->keyBy('rule_type');
$this->assertTrue($sectionRules->has('max_selected'), 'max_priorities should canonicalise to max_selected');
$this->assertSame(3, json_decode((string) $sectionRules['max_selected']->parameters, true)['value']);
$this->assertFalse($sectionRules->has('max_priorities'), 'legacy key must not survive');
$libRules = DB::table('form_field_validation_rules')
->where('owner_type', 'form_field_library')
->where('owner_id', $libAId)
->get()->keyBy('rule_type');
$this->assertTrue($libRules->has('regex'));
$this->assertSame(
'/^[A-Z]{3}$/',
json_decode((string) $libRules['regex']->parameters, true)['pattern'],
);
}
public function test_tag_categories_and_storage_disk_skipped_for_commit_5(): void
{
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
$fieldId = $this->seedFieldWithJson([
'field_type' => 'TAG_PICKER',
'validation_rules' => [
'tag_categories' => ['Veiligheid'],
'storage_disk' => 'local',
],
]);
$this->artisan('migrate')->assertSuccessful();
$rows = DB::table('form_field_validation_rules')
->where('owner_id', $fieldId)
->get();
$this->assertCount(0, $rows, 'configs keys must not land in the validation-rules table');
}
public function test_required_and_unique_skipped_with_warn(): void
{
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
$fieldId = $this->seedFieldWithJson([
'field_type' => 'TEXT',
'validation_rules' => [
'required' => true,
'unique' => true,
'min' => 2,
],
]);
$this->artisan('migrate')->assertSuccessful();
$rows = DB::table('form_field_validation_rules')
->where('owner_id', $fieldId)
->pluck('rule_type')
->all();
sort($rows);
$this->assertSame(['min_length'], $rows, 'only min_length should land (required/unique skipped)');
}
public function test_unknown_top_level_key_fails_migration(): void
{
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
$this->seedFieldWithJson([
'field_type' => 'TEXT',
'validation_rules' => ['nonsense_key' => 42],
]);
$this->expectException(\RuntimeException::class);
$this->artisan('migrate');
}
public function test_unmapped_field_type_for_min_max_fails_migration(): void
{
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
$this->seedFieldWithJson([
'field_type' => 'BOOLEAN',
'validation_rules' => ['min' => 1],
]);
$this->expectException(\RuntimeException::class);
$this->artisan('migrate');
}
public function test_rollback_reconstructs_canonical_json_on_source_tables(): void
{
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
[$numberId] = $this->seedFields();
$this->artisan('migrate')->assertSuccessful();
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
// Only the backfill rolled back — the create-table migration still
// applied, so rows remain accessible (until we step back once more).
$this->assertTrue(Schema::hasTable('form_field_validation_rules'));
$field = DB::table('form_fields')->where('id', $numberId)->first();
$decoded = json_decode((string) $field->validation_rules, true);
// Rollback reconstructs using canonical keys — the legacy `min`/`max`
// are intentionally NOT resurrected (post-rename semantic).
$this->assertSame(16, $decoded['min_value']);
$this->assertSame(99, $decoded['max_value']);
}
/** @return array{0:string,1:string,2:string,3:string} */
private function seedFields(): array
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$number = (string) Str::ulid();
$text = (string) Str::ulid();
$date = (string) Str::ulid();
$section = (string) Str::ulid();
DB::table('form_fields')->insert([
$this->row($number, $schema->id, 'NUMBER', 'leeftijd',
['min' => 16, 'max' => 99]),
$this->row($text, $schema->id, 'TEXT', 'postcode',
['min' => 5, 'max' => 80]),
$this->row($date, $schema->id, 'DATE', 'startdatum',
['min' => '2026-01-01']),
$this->row($section, $schema->id, 'SECTION_PRIORITY', 'sectie-voorkeur',
['max_priorities' => 3]),
]);
return [$number, $text, $date, $section];
}
/** @param array<string, mixed> $validationRules */
private function row(string $id, string $schemaId, string $fieldType, string $slug, array $validationRules): array
{
return [
'id' => $id,
'form_schema_id' => $schemaId,
'field_type' => $fieldType,
'slug' => $slug,
'label' => $slug,
'validation_rules' => json_encode($validationRules),
'value_storage_hint' => 'json',
'sort_order' => 0,
'created_at' => now(),
'updated_at' => now(),
];
}
/** @return array{0:string} */
private function seedLibrary(): array
{
$org = Organisation::factory()->create();
$lib = (string) Str::ulid();
DB::table('form_field_library')->insert([
[
'id' => $lib,
'organisation_id' => $org->id,
'name' => 'License plate bibliotheek',
'slug' => 'kenteken-lib',
'field_type' => 'TEXT',
'label' => 'Kenteken',
'validation_rules' => json_encode(['regex' => '/^[A-Z]{3}$/']),
'default_is_required' => false,
'default_is_filterable' => false,
'usage_count' => 0,
'is_system' => false,
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
]);
return [$lib];
}
/** @param array<string, mixed> $attrs */
private function seedFieldWithJson(array $attrs): string
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$id = (string) Str::ulid();
DB::table('form_fields')->insert([[
'id' => $id,
'form_schema_id' => $schema->id,
'field_type' => $attrs['field_type'],
'slug' => 'f-'.Str::lower(Str::random(4)),
'label' => 'field',
'validation_rules' => json_encode($attrs['validation_rules']),
'value_storage_hint' => 'json',
'sort_order' => 0,
'created_at' => now(),
'updated_at' => now(),
]]);
return $id;
}
}

View File

@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\ValidationRules;
use App\Enums\FormBuilder\FormFieldValidationRuleType;
use App\Exceptions\FormBuilder\UnknownValidationRuleTypeException;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormFieldValidationRule;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use App\Services\FormBuilder\FormFieldValidationRuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Spatie\Activitylog\Models\Activity;
use Tests\TestCase;
final class FormFieldValidationRuleServiceTest extends TestCase
{
use RefreshDatabase;
private FormFieldValidationRuleService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(FormFieldValidationRuleService::class);
}
public function test_replace_rules_is_transactional_delete_then_insert(): void
{
$field = $this->makeField();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MinLength, ['value' => 1])->create();
$this->service->replaceRules($field, [
['rule_type' => 'min_length', 'parameters' => ['value' => 5]],
['rule_type' => 'max_length', 'parameters' => ['value' => 40]],
]);
$rules = $this->service->rulesFor($field);
$this->assertCount(2, $rules);
$this->assertSame(5, $rules->firstWhere('rule_type', FormFieldValidationRuleType::MinLength)->parameters['value']);
$this->assertSame(40, $rules->firstWhere('rule_type', FormFieldValidationRuleType::MaxLength)->parameters['value']);
}
public function test_empty_specs_array_clears_all_rules(): void
{
$field = $this->makeField();
FormFieldValidationRule::factory()->forField($field)->create();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MaxLength, ['value' => 10])->create();
$this->service->replaceRules($field, []);
$this->assertCount(0, $this->service->rulesFor($field));
}
public function test_unknown_rule_type_is_rejected(): void
{
$field = $this->makeField();
$this->expectException(UnknownValidationRuleTypeException::class);
$this->service->replaceRules($field, [
['rule_type' => 'not_a_real_rule', 'parameters' => []],
]);
}
public function test_bad_parameter_shape_is_rejected(): void
{
$field = $this->makeField();
$this->expectException(UnknownValidationRuleTypeException::class);
$this->service->replaceRules($field, [
['rule_type' => 'min_length', 'parameters' => ['value' => 'not-an-int']],
]);
}
public function test_allowed_mime_types_requires_array(): void
{
$field = $this->makeField();
$this->expectException(UnknownValidationRuleTypeException::class);
$this->service->replaceRules($field, [
['rule_type' => 'allowed_mime_types', 'parameters' => ['mime_types' => 'not-an-array']],
]);
}
public function test_callback_rejects_unregistered_key(): void
{
Config::set('form_builder.validation_callbacks', []);
$field = $this->makeField();
$this->expectException(UnknownValidationRuleTypeException::class);
$this->service->replaceRules($field, [
['rule_type' => 'callback', 'parameters' => ['key' => 'unregistered_callback']],
]);
}
public function test_callback_accepts_registered_key(): void
{
Config::set('form_builder.validation_callbacks', [
'kvk_lookup' => \stdClass::class,
]);
$field = $this->makeField();
$this->service->replaceRules($field, [
['rule_type' => 'callback', 'parameters' => ['key' => 'kvk_lookup']],
]);
$rules = $this->service->rulesFor($field);
$this->assertSame('kvk_lookup', $rules->first()->parameters['key']);
}
public function test_replace_emits_field_validation_rules_replaced_activity_log(): void
{
$field = $this->makeField();
$this->service->replaceRules($field, [
['rule_type' => 'min_length', 'parameters' => ['value' => 3]],
]);
$entry = Activity::query()
->where('subject_type', 'form_field')
->where('subject_id', $field->id)
->where('description', 'field.validation_rules_replaced')
->first();
$this->assertNotNull($entry);
$this->assertSame(1, (int) $entry->properties['count']);
}
public function test_replace_on_library_does_not_emit_field_activity_log(): void
{
// Convention-match with WS-5a: library-level changes are silent in
// activity log; only the FormField subject gets the semantic event.
$library = FormFieldLibrary::factory()->create([
'organisation_id' => Organisation::factory()->create()->id,
]);
$this->service->replaceRules($library, [
['rule_type' => 'min_length', 'parameters' => ['value' => 3]],
]);
$entry = Activity::query()
->where('subject_type', 'form_field_library')
->where('description', 'field.validation_rules_replaced')
->first();
$this->assertNull($entry);
}
public function test_copy_rules_clones_every_column(): void
{
$org = Organisation::factory()->create();
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
FormFieldValidationRule::factory()->forLibrary($library)
->ofType(FormFieldValidationRuleType::MinLength, ['value' => 3])->create();
FormFieldValidationRule::factory()->forLibrary($library)
->ofType(FormFieldValidationRuleType::MaxLength, ['value' => 40])->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
$this->service->copyRules($library, $field);
$rules = $this->service->rulesFor($field);
$this->assertCount(2, $rules);
$this->assertSame(3, $rules->firstWhere('rule_type', FormFieldValidationRuleType::MinLength)->parameters['value']);
$this->assertSame(40, $rules->firstWhere('rule_type', FormFieldValidationRuleType::MaxLength)->parameters['value']);
}
public function test_to_json_shape_empty_collection_returns_null(): void
{
$field = $this->makeField();
$this->assertNull($this->service->toJsonShape($this->service->rulesFor($field)));
}
public function test_to_json_shape_flattens_known_rule_types(): void
{
$field = $this->makeField();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MinLength, ['value' => 5])->create();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::Regex, ['pattern' => '/^x/'])->create();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::AllowedMimeTypes, ['mime_types' => ['image/png']])->create();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::EmailFormat, [])->create();
$shape = $this->service->toJsonShape($this->service->rulesFor($field));
$this->assertSame(5, $shape['min_length']);
$this->assertSame('/^x/', $shape['regex']);
$this->assertSame(['image/png'], $shape['allowed_mime_types']);
$this->assertTrue($shape['email_format']);
}
private function makeField(): FormField
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
return FormField::factory()->create(['form_schema_id' => $schema->id]);
}
}

View File

@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\ValidationRules;
use App\Enums\FormBuilder\FormFieldValidationRuleType;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormFieldValidationRule;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use App\Services\FormBuilder\FormFieldService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* FormFieldService::insertFromLibrary must row-copy validation rules from
* the library entry to the new field (addendum Q3 row-copy mandate, paired
* with the existing bindings row-copy from WS-5a).
*/
final class InsertFromLibraryCopiesRulesTest extends TestCase
{
use RefreshDatabase;
public function test_library_rules_are_copied_to_new_field(): void
{
$org = Organisation::factory()->create();
$library = FormFieldLibrary::factory()->create([
'organisation_id' => $org->id,
'slug' => 'kenteken',
]);
FormFieldValidationRule::factory()->forLibrary($library)
->ofType(FormFieldValidationRuleType::Regex, ['pattern' => '/^[A-Z]{3}$/'])->create();
FormFieldValidationRule::factory()->forLibrary($library)
->ofType(FormFieldValidationRuleType::MaxLength, ['value' => 8])->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
/** @var FormField $field */
$field = app(FormFieldService::class)->insertFromLibrary($schema, $library);
$rules = FormFieldValidationRule::query()
->where('owner_type', 'form_field')
->where('owner_id', $field->id)
->get()
->keyBy(fn ($r) => $r->rule_type->value);
$this->assertCount(2, $rules);
$this->assertSame('/^[A-Z]{3}$/', $rules['regex']->parameters['pattern']);
$this->assertSame(8, $rules['max_length']->parameters['value']);
}
public function test_library_without_rules_produces_field_without_rules(): void
{
$org = Organisation::factory()->create();
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
/** @var FormField $field */
$field = app(FormFieldService::class)->insertFromLibrary($schema, $library);
$count = FormFieldValidationRule::query()
->where('owner_type', 'form_field')
->where('owner_id', $field->id)
->count();
$this->assertSame(0, $count);
}
}

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\ValidationRules;
use App\Enums\FormBuilder\FormFieldType;
use App\Enums\FormBuilder\FormFieldValidationRuleType;
use App\Enums\FormBuilder\FormSchemaSnapshotMode;
use App\Enums\FormBuilder\FormSubmissionMode;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldValidationRule;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use App\Services\FormBuilder\FormSubmissionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* `form_submissions.schema_snapshot.fields[*].validation_rules` is now
* sourced from the relational table via
* `FormFieldValidationRuleService::toJsonShape()`. Given a field with
* known rules, the snapshot JSON embeds the canonical shape parity
* check against a freshly-rendered resource output.
*/
final class SchemaSnapshotValidationRulesParityTest extends TestCase
{
use RefreshDatabase;
public function test_snapshot_embeds_canonical_validation_rules_shape(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create([
'organisation_id' => $org->id,
'submission_mode' => FormSubmissionMode::SINGLE,
'snapshot_mode' => FormSchemaSnapshotMode::ON_SUBMIT,
]);
$field = FormField::factory()->create([
'form_schema_id' => $schema->id,
'field_type' => FormFieldType::TEXT->value,
'slug' => 'voornaam',
]);
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MinLength, ['value' => 2])->create();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MaxLength, ['value' => 40])->create();
$service = app(FormSubmissionService::class);
$snapshot = $this->invokeBuildSnapshot($service, $schema);
$fieldEntry = collect($snapshot['fields'])->firstWhere('slug', 'voornaam');
$this->assertNotNull($fieldEntry);
$this->assertSame([
'min_length' => 2,
'max_length' => 40,
], $fieldEntry['validation_rules']);
}
public function test_snapshot_validation_rules_null_when_no_rules(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
FormField::factory()->create([
'form_schema_id' => $schema->id,
'slug' => 'noot',
]);
$service = app(FormSubmissionService::class);
$snapshot = $this->invokeBuildSnapshot($service, $schema);
$entry = collect($snapshot['fields'])->firstWhere('slug', 'noot');
$this->assertNull($entry['validation_rules']);
}
/** @return array<string, mixed> */
private function invokeBuildSnapshot(FormSubmissionService $service, FormSchema $schema): array
{
$ref = new \ReflectionMethod($service, 'buildSnapshot');
$ref->setAccessible(true);
return $ref->invoke($service, $schema);
}
}

View File

@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\ValidationRules;
use App\Enums\FormBuilder\FormFieldType;
use App\Enums\FormBuilder\FormFieldValidationRuleType;
use App\Http\Resources\FormBuilder\FormFieldLibraryResource;
use App\Http\Resources\FormBuilder\FormFieldResource;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormFieldValidationRule;
use App\Models\FormBuilder\FormSchema;
use App\Models\Organisation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* API-resource contract: the `validation_rules` key in the resource output
* is now sourced from the relational table via
* `FormFieldValidationRuleService::toJsonShape()`. The shape is the
* canonical flat bag (new post-WS-5b key names). Parity means: same
* semantic rule same bag entry.
*/
final class ValidationRulesResourceParityTest extends TestCase
{
use RefreshDatabase;
public function test_form_field_resource_emits_canonical_shape_from_relational_rules(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create([
'form_schema_id' => $schema->id,
'field_type' => FormFieldType::TEXT->value,
]);
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MinLength, ['value' => 3])->create();
FormFieldValidationRule::factory()->forField($field)
->ofType(FormFieldValidationRuleType::MaxLength, ['value' => 40])->create();
$rendered = (new FormFieldResource($field->fresh()))->toArray(request());
$this->assertSame([
'min_length' => 3,
'max_length' => 40,
], $rendered['validation_rules']);
}
public function test_form_field_resource_emits_null_when_no_rules(): void
{
$org = Organisation::factory()->create();
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
$rendered = (new FormFieldResource($field->fresh()))->toArray(request());
$this->assertNull($rendered['validation_rules']);
}
public function test_form_field_library_resource_emits_canonical_shape(): void
{
$org = Organisation::factory()->create();
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
FormFieldValidationRule::factory()->forLibrary($library)
->ofType(FormFieldValidationRuleType::AllowedMimeTypes, ['mime_types' => ['image/png', 'image/jpeg']])->create();
$rendered = (new FormFieldLibraryResource($library->fresh()))->toArray(request());
$this->assertSame([
'allowed_mime_types' => ['image/png', 'image/jpeg'],
], $rendered['validation_rules']);
}
}