Files
crewli/api/app/Services/FormBuilder/FormFieldRuleBuilder.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

213 lines
6.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\FormBuilder;
use App\Enums\FormBuilder\FormFieldType;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormSchema;
/**
* Build Laravel validation rules dynamically from a schema's form_fields.
*
* Two modes (S2c D8):
* - strict(): for the final submit pipeline. is_required fields are
* required; SELECT/RADIO values must be in options; multi-value
* types must be arrays; type rules (email/url/date/numeric/boolean)
* are enforced.
* - relaxed(): for auto-save drafts. Every rule becomes nullable;
* options lists still constrain (a SELECT can't silently accept
* garbage, even mid-draft), but required stays off.
*
* Rule shape returned targets `values.{slug}` and `values.{slug}.*` keys
* so FormRequests can merge this into their own `values` wrapper:
*
* return array_merge(['values' => ['required', 'array']], $ruleBuilder->strict($schema));
*/
final class FormFieldRuleBuilder
{
public function __construct(
private readonly FormFieldValidationRuleService $validationRuleService,
) {}
/**
* @return array<string, array<int, string>>
*/
public function strict(FormSchema $schema): array
{
return $this->build($schema, strict: true);
}
/**
* @return array<string, array<int, string>>
*/
public function relaxed(FormSchema $schema): array
{
return $this->build($schema, strict: false);
}
/**
* @return array<string, array<int, string>>
*/
private function build(FormSchema $schema, bool $strict): array
{
$fields = $schema->fields()->get();
$rules = [];
foreach ($fields as $field) {
if (! (bool) $field->is_portal_visible || (bool) $field->is_admin_only) {
continue;
}
if (in_array($field->field_type, [FormFieldType::HEADING->value, FormFieldType::PARAGRAPH->value], true)) {
continue;
}
$key = 'values.'.$field->slug;
$isMulti = $this->isMultiValue($field);
$primaryRules = [];
if ($strict && (bool) $field->is_required) {
$primaryRules[] = $isMulti ? 'present' : 'required';
} else {
$primaryRules[] = 'sometimes';
$primaryRules[] = 'nullable';
}
if ($isMulti) {
$primaryRules[] = 'array';
$rules[$key] = $primaryRules;
foreach ($this->itemRulesFor($field, $strict) as $itemRule) {
$rules[$key.'.*'][] = $itemRule;
}
continue;
}
foreach ($this->scalarTypeRules($field) as $r) {
$primaryRules[] = $r;
}
foreach ($this->validationRuleShortcuts($field) as $r) {
$primaryRules[] = $r;
}
$rules[$key] = $primaryRules;
}
return $rules;
}
private function isMultiValue(FormField $field): bool
{
return in_array($field->field_type, [
FormFieldType::MULTISELECT->value,
FormFieldType::CHECKBOX_LIST->value,
FormFieldType::TAG_PICKER->value,
FormFieldType::AVAILABILITY_PICKER->value,
FormFieldType::SECTION_PRIORITY->value,
FormFieldType::TABLE_ROWS->value,
], true);
}
/**
* @return array<int, string>
*/
private function scalarTypeRules(FormField $field): array
{
return match ($field->field_type) {
FormFieldType::EMAIL->value => ['email:rfc'],
FormFieldType::URL->value => ['url'],
FormFieldType::NUMBER->value => ['numeric'],
FormFieldType::DATE->value => ['date_format:Y-m-d'],
FormFieldType::DATETIME->value => ['date'],
FormFieldType::BOOLEAN->value => ['boolean'],
FormFieldType::PHONE->value => ['regex:/^[+]?[0-9\s\-()]{4,25}$/'],
FormFieldType::SELECT->value, FormFieldType::RADIO->value => $this->inOptionsRule($field),
default => ['string'],
};
}
/**
* @return array<int, string>
*/
private function itemRulesFor(FormField $field, bool $strict): array
{
$rules = [];
if ($strict && (bool) $field->is_required) {
$rules[] = 'required';
} else {
$rules[] = 'nullable';
}
return match ($field->field_type) {
FormFieldType::MULTISELECT->value, FormFieldType::CHECKBOX_LIST->value => array_merge($rules, $this->inOptionsRule($field)),
FormFieldType::TAG_PICKER->value => array_merge($rules, ['string', 'max:30']),
FormFieldType::AVAILABILITY_PICKER->value => array_merge($rules, ['string', 'max:30']),
FormFieldType::SECTION_PRIORITY->value => array_merge($rules, ['array:section_id,priority']),
FormFieldType::TABLE_ROWS->value => array_merge($rules, ['array']),
default => $rules,
};
}
/**
* @return array<int, string>
*/
private function inOptionsRule(FormField $field): array
{
$options = $this->scalarOptions($field);
if ($options === []) {
return [];
}
return ['in:'.implode(',', $options)];
}
/**
* @return array<int, string>
*/
private function scalarOptions(FormField $field): array
{
return $field->options()->pluck('value')->all();
}
/**
* Shortcuts picked up from the relational validation-rules table.
* Service-layer FormValueService does the deeper min/max/regex/unique
* enforcement — these are quick boundary checks surfaced at the
* Request layer when cheap.
*
* Laravel's `min:N` / `max:N` already do the right thing for both
* numeric inputs (value comparison) and strings (length check), so
* `min_length`/`min_value` both emit the same `min:N` rule.
*
* @return array<int, string>
*/
private function validationRuleShortcuts(FormField $field): array
{
$rules = [];
$v = $this->validationRuleService->toJsonShape($field->validationRules);
if (! is_array($v)) {
return $rules;
}
if (isset($v['min_value']) && is_numeric($v['min_value'])) {
$rules[] = 'min:'.(string) $v['min_value'];
}
if (isset($v['max_value']) && is_numeric($v['max_value'])) {
$rules[] = 'max:'.(string) $v['max_value'];
}
if (isset($v['min_length']) && is_numeric($v['min_length'])) {
$rules[] = 'min:'.(string) $v['min_length'];
}
if (isset($v['max_length']) && is_numeric($v['max_length'])) {
$rules[] = 'max:'.(string) $v['max_length'];
}
if (isset($v['regex']) && is_string($v['regex'])) {
$rules[] = 'regex:'.$v['regex'];
}
return $rules;
}
}