Files
crewli/api/app/FormBuilder/Bindings/FormBindingApplicator.php
bert.hausmans 762fc62efa feat(form-builder): wire D1 building blocks into ApplyBindings + add deadline wrapper
Per RFC-WS-6 §Q1 v1.3 addition 1, 4 + §Q3 v1.3 addition 2 + ARCH-BINDINGS §5.3.

- FormBindingApplicator::withDeadline(int) returns a clone configured to
  throw FormBindingApplicatorTimeoutException if apply() exceeds the
  deadline. Soft post-call microtime check; cannot interrupt mid-query
  but catches the long tail. apply() refactored to single-return so the
  deadline check sits at one site instead of duplicated.
- ApplyBindingsOnFormSubmit::handle:
  - Initial identity_match_status='pending' write inside inner
    transaction (when subject is or becomes a person) so HTTP response
    carries the right state for the IdentityMatchBanner first-paint
    copy. Final state comes from the queued TriggerPersonIdentityMatch
    (D2 Phase C).
  - Wraps apply() with config('form_builder.apply_deadline_seconds', 5).
  - Catch block uses FormBindingExceptionClassifier::classify to write
    failure_response_code in the outer transaction alongside
    apply_status=FAILED. submission_id from the exception (when in the
    binding-applicator hierarchy) is also captured in context JSON.

Tests added in Phase I.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 02:55:11 +02:00

273 lines
11 KiB
PHP

<?php
declare(strict_types=1);
namespace App\FormBuilder\Bindings;
use App\Enums\FormBuilder\BindingTargetType;
use App\Enums\FormBuilder\FormFieldBindingMergeStrategy;
use App\Exceptions\FormBuilder\FormBindingApplicatorException;
use App\Exceptions\FormBuilder\FormBindingApplicatorTimeoutException;
use App\Exceptions\FormBuilder\FormBindingInfraException;
use App\Exceptions\FormBuilder\FormBindingSchemaConfigException;
use App\FormBuilder\Purposes\PurposeRegistry;
use App\Models\FormBuilder\FormSubmission;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* RFC-WS-6 §3 — orchestrator for the binding pipeline. Calls the
* subject resolver, the conflict resolver, and writes target attributes.
*
* - Q4: caller MUST be inside a DB::transaction; this method does
* not open its own. Per-binding write failures are captured in the
* result, not thrown. Catastrophic failures (no transaction,
* unknown purpose, missing schema) bubble.
* - Q7: per-strategy null-winner matrix via
* FormFieldBindingMergeStrategy::nullWinnerBehaviour().
* - Q9: subject resolution via per-purpose PurposeSubjectResolver.
* - Q10: optional sectionId for future section-level apply.
* - Q12: hierarchical activity log via BindingActivityLogger.
* - v1.3 Q1 add 4: optional deadline (withDeadline()) — soft post-call
* microtime check throwing FormBindingApplicatorTimeoutException.
* Cannot interrupt mid-query; intended to catch the long-tail of
* slow applies before they hang the public flow.
*/
// Not final + not readonly: listener tests need to override `apply()` for
// throw-path coverage (Mockery can't mock final classes; PHP doesn't allow
// extending readonly with non-readonly child). Properties stay readonly
// individually to preserve immutability.
class FormBindingApplicator
{
/**
* Per RFC-WS-6 §Q1 v1.3 addition 4 — soft deadline (seconds). NULL
* means "no deadline check" (default). Set via withDeadline() so the
* value travels with a clone and the original instance stays
* deadline-free for other callers (e.g. the retry-service path,
* which currently does not bound apply() — see ARCH-BINDINGS §5.3).
*/
private ?int $deadlineSeconds = null;
public function __construct(
private readonly PurposeRegistry $purposeRegistry,
private readonly BindingConflictResolver $conflictResolver,
private readonly BindingTypeRegistry $typeRegistry,
private readonly BindingActivityLogger $activityLogger,
) {}
/**
* Returns a clone configured to throw FormBindingApplicatorTimeoutException
* if apply() exceeds the given deadline.
*
* Per RFC-WS-6 §Q1 v1.3 addition 4 + ARCH-BINDINGS §5.3.
*
* Implementation note: this is a soft post-call deadline check via
* microtime. It cannot interrupt mid-query — for that, configure MySQL
* connection timeouts at the database driver level. The soft deadline
* is sufficient to prevent runaway apply() calls from hanging the
* public flow indefinitely; a typical apply() takes <100ms, so a 5s
* deadline catches the long tail.
*/
public function withDeadline(int $seconds): self
{
$clone = clone $this;
$clone->deadlineSeconds = $seconds;
return $clone;
}
/**
* @throws FormBindingApplicatorException
*/
public function apply(FormSubmission $submission, ?string $sectionId = null): BindingPassResult
{
$start = microtime(true);
if (DB::transactionLevel() < 1) {
throw new FormBindingInfraException(
submissionId: (string) $submission->id,
message: 'FormBindingApplicator must be invoked inside DB::transaction',
);
}
/** @var \App\Models\FormBuilder\FormSchema|null $schema */
$schema = $submission->schema;
if ($schema === null) {
throw new FormBindingSchemaConfigException(
submissionId: (string) $submission->id,
message: "schema null for submission {$submission->id}",
);
}
$purposeValue = $schema->purpose->value;
if (! $this->purposeRegistry->has($purposeValue)) {
throw new FormBindingSchemaConfigException(
submissionId: (string) $submission->id,
message: "purpose '{$purposeValue}' not registered",
);
}
$resolver = $this->purposeRegistry->subjectResolverFor($purposeValue);
$subject = $resolver->resolveOrProvision($submission);
if (! $subject instanceof Model) {
// Anonymous-allowed (incident_report). No bindings to apply.
$result = new BindingPassResult(
formSubmissionId: (string) $submission->id,
provisionedSubjectType: null,
provisionedSubjectId: null,
applications: [],
);
} else {
$resolved = $this->conflictResolver->resolve($submission, $sectionId);
// Persist subject identity for the result + apply each binding.
$applications = [];
foreach ($resolved as $binding) {
// Skip identity-key bindings — the resolver already used them
// for subject lookup in EventRegistration's PersonProvisioner
// path. Writing them again is a no-op at best, a clobber at
// worst.
if ($binding->isIdentityKey) {
continue;
}
$applications[] = $this->applyOne($subject, $binding);
}
$result = new BindingPassResult(
formSubmissionId: (string) $submission->id,
provisionedSubjectType: $this->morphAlias($subject),
provisionedSubjectId: (string) $subject->getKey(),
applications: $applications,
);
}
$this->activityLogger->logPass($submission, $result);
$this->checkDeadline((string) $submission->id, $start);
return $result;
}
/**
* Throws FormBindingApplicatorTimeoutException if a deadline is
* configured and the elapsed wall-clock time exceeds it.
*/
private function checkDeadline(string $submissionId, float $startMicrotime): void
{
if ($this->deadlineSeconds === null) {
return;
}
$elapsed = microtime(true) - $startMicrotime;
if ($elapsed > $this->deadlineSeconds) {
throw new FormBindingApplicatorTimeoutException(
submissionId: $submissionId,
message: sprintf(
'FormBindingApplicator exceeded deadline of %ds (elapsed: %.2fs) for submission %s',
$this->deadlineSeconds,
$elapsed,
$submissionId,
),
);
}
}
private function applyOne(Model $subject, ResolvedBinding $binding): BindingApplicationResult
{
try {
// Defensive: BindingTypeRegistry validates Append-against-scalar
// at publish time; runtime check is a failsafe for live-table
// edits between publish and apply.
$this->typeRegistry->validateAppendStrategy(
$binding->targetEntity,
$binding->targetAttribute,
$binding->mergeStrategy,
);
$oldValue = $subject->getAttribute($binding->targetAttribute);
$newValue = $this->computeNewValue($oldValue, $binding);
if ($newValue === self::NO_OP) {
return BindingApplicationResult::succeeded(
bindingId: $binding->bindingId,
targetEntity: $binding->targetEntity,
targetAttribute: $binding->targetAttribute,
oldValue: $oldValue,
newValue: $oldValue,
);
}
$subject->setAttribute($binding->targetAttribute, $newValue);
$subject->save();
return BindingApplicationResult::succeeded(
bindingId: $binding->bindingId,
targetEntity: $binding->targetEntity,
targetAttribute: $binding->targetAttribute,
oldValue: $oldValue,
newValue: $newValue,
);
} catch (Throwable $e) {
return BindingApplicationResult::failed(
bindingId: $binding->bindingId,
targetEntity: $binding->targetEntity,
targetAttribute: $binding->targetAttribute,
e: $e,
);
}
}
private const NO_OP = '__binding_noop_sentinel__';
private function computeNewValue(mixed $oldValue, ResolvedBinding $binding): mixed
{
$newValue = $binding->value;
$strategy = $binding->mergeStrategy;
// Per-strategy matrix. RFC §3 Q7.
if ($newValue === null) {
$behaviour = $strategy->nullWinnerBehaviour();
return match ($behaviour) {
'write' => null,
'noop' => self::NO_OP,
'conditional' => $oldValue === null ? null : self::NO_OP,
default => self::NO_OP,
};
}
return match ($strategy) {
FormFieldBindingMergeStrategy::Overwrite => $newValue,
FormFieldBindingMergeStrategy::Append => $this->appendCollection($oldValue, $newValue, $binding),
FormFieldBindingMergeStrategy::Replace => $oldValue === null ? $newValue : self::NO_OP,
FormFieldBindingMergeStrategy::FirstWriteWins => $oldValue === null ? $newValue : self::NO_OP,
};
}
private function appendCollection(mixed $oldValue, mixed $newValue, ResolvedBinding $binding): mixed
{
if ($binding->targetType !== BindingTargetType::COLLECTION) {
// Defensive — publish guard should prevent this. Throwing
// gets the failure into BindingApplicationResult::failed.
throw new \InvalidArgumentException(
"merge_strategy=append requires COLLECTION target; got {$binding->targetType->value}",
);
}
$current = is_array($oldValue) ? $oldValue : [];
$incoming = is_array($newValue) ? $newValue : [$newValue];
// Set semantics: dedupe via array_unique. Preserves insertion order
// for stable activity log output.
$merged = array_values(array_unique(array_merge($current, $incoming), SORT_REGULAR));
return $merged;
}
private function morphAlias(Model $subject): string
{
return $subject->getMorphClass();
}
}