completed * transition is atomic (callable returns true for exactly one caller), so * replays and races finalize at most once. */ final class CaptureFinalizer { public const COMPLETED = 'completed'; // this call finalized the donation public const DUPLICATE = 'duplicate'; // already finalized / not pending public const PENDING = 'pending'; // capture looks off; donation left pending /** * @param object|array $row Donation row (status, total_minor, currency). * @param callable $markCompleted fn(int $id, string $captureId): bool atomic pending->completed * @param callable $notifyApplied fn(int $id): void * @param callable|null $recordCapture fn(int $id, string $captureId): void Called when PayPal returned a capture id but the * donation is NOT finalized (PENDING/under review/amount mismatch). Persists the id so the * row is never mistaken for an abandoned checkout and the later webhook can find it. */ public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied, ?callable $recordCapture = null ): string { $r = (object) $row; if ( 'pending' !== (string) $r->status ) { return self::DUPLICATE; } if ( 'COMPLETED' !== $paypalStatus || '' === $captureId ) { return self::pendingWith( $r, $captureId, $recordCapture ); } if ( ! $amount || $amount->minor !== (int) $r->total_minor || $amount->currency !== (string) $r->currency ) { return self::pendingWith( $r, $captureId, $recordCapture ); } if ( $markCompleted( (int) $r->id, $captureId ) ) { $notifyApplied( (int) $r->id ); return self::COMPLETED; } return self::DUPLICATE; } private static function pendingWith( object $r, string $captureId, ?callable $recordCapture ): string { if ( '' !== $captureId && null !== $recordCapture ) { $recordCapture( (int) $r->id, $captureId ); } return self::PENDING; } }