add form submission handling and confirmation emails

Validate form submissions and action configuration, execute finishers with submission context, and return JSON success or error responses. Add configurable confirmation emails to submitters and report failed submissions in the form UI.

Harden database and admin email finishers, and add submission handler and confirmation email checks.
This commit is contained in:
2026-11-24 11:26:37 +01:00
parent 80e60d6823
commit c507618b90
10 changed files with 593 additions and 47 deletions
@@ -1,29 +1,36 @@
<?php
namespace Plugi\Extensions\Form\Finishers;
use Plugi\Extensions\Form\DefinitionsRepository;
class DefaultFinisher {
public $formId;
public $form;
public $data;
public function __construct()
public $submission;
public $options;
public function __construct(array $context = [], array $options = [])
{
$formRepository = new DefinitionsRepository();
$this->formId = $_GET['id'] ?? 0;
$this->form = $formRepository->findWithId($this->formId);
$this->data = file_get_contents('php://input');
$this->formId = $context['formId'] ?? null;
$this->form = $context['form'] ?? [];
$this->data = $context['rawData'] ?? '';
$this->submission = $context['submission'] ?? [];
$this->options = $options;
}
public function execute (): bool {
return true;
}
public function getFormFields (): array {
return json_decode($this->form['fields'], true);
return $this->form['formFields'] ?? [];
}
public function getEntryFields (): array {
return json_decode($this->data, true)['fields'];
return $this->submission['fields'] ?? [];
}
public function getFormName (): string {
return $this->form['name'];
return (string) ($this->form['name'] ?? '');
}
}
@@ -6,10 +6,9 @@ class SaveEntryToDatabase extends DefaultFinisher
public function execute(): bool
{
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
$entriesRepository->create([
return $entriesRepository->create([
'formId' => $this->formId,
'data' => $this->data,
]);
return true;
]) !== null;
}
}
@@ -0,0 +1,43 @@
<?php
namespace Plugi\Extensions\Form\Finishers;
class SendConfirmationEmailToSubmitter extends DefaultFinisher
{
public function execute(): bool
{
$recipientField = $this->options['recipientField'] ?? null;
if (!is_string($recipientField) || $recipientField === '') {
return false;
}
$emailFieldExists = false;
foreach ($this->getFormFields() as $field) {
if (($field['name'] ?? null) === $recipientField && ($field['type'] ?? null) === 'email') {
$emailFieldExists = true;
break;
}
}
if (!$emailFieldExists) {
return false;
}
$recipient = $this->getEntryFields()[$recipientField] ?? null;
if (!is_string($recipient) || filter_var($recipient, FILTER_VALIDATE_EMAIL) === false) {
return false;
}
$subject = $this->options['subject'] ?? null;
$message = $this->options['message'] ?? null;
if (!is_string($subject) || trim($subject) === '' || strpbrk($subject, "\r\n") !== false || !is_string($message) || trim($message) === '') {
return false;
}
return $this->sendMail($recipient, $subject, $message);
}
protected function sendMail(string $recipient, string $subject, string $message): bool
{
return mail($recipient, $subject, $message);
}
}
@@ -7,7 +7,12 @@ class SendEmailToAdmin extends DefaultFinisher
{
public function execute(): bool
{
$to = Extensions::getSettings('form')['email']['value'];
$settings = Extensions::getSettings('form');
$to = $settings['email']['value'] ?? null;
if (!is_string($to) || filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
return false;
}
$subject = 'Form submission: '.$this->getFormName();
$message = $this->getNiceFields();
return mail(
@@ -21,7 +26,15 @@ class SendEmailToAdmin extends DefaultFinisher
private function getNiceFields(): string {
$text = '';
foreach ($this->getFormFields() as $field) {
$text .= $field['label'] . ': ' . $this->getEntryFields()[$field['name']] . "\n";
$name = $field['name'] ?? '';
$label = $field['label'] ?? $name;
$value = $this->getEntryFields()[$name] ?? '';
if (is_array($value)) {
$value = implode(', ', array_map('strval', $value));
} elseif (!is_scalar($value)) {
$value = '';
}
$text .= $label . ': ' . $value . "\n";
}
return $text;
}
@@ -9,6 +9,10 @@ return [
'sendMailToAdmin' => [
'class' => \Plugi\Extensions\Form\Finishers\SendEmailToAdmin::class,
'label' => 'Send email to admin'
],
'sendConfirmationEmailToSubmitter' => [
'class' => \Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter::class,
'label' => 'Send confirmation email to submitter'
]
]
];
@@ -0,0 +1,222 @@
<?php
namespace Plugi\Extensions\Form;
use Plugi\Extensions\Form\Finishers\DefaultFinisher;
use Plugi\Extensions\Form\Finishers\FinishersRepository;
class SubmissionHandler
{
private $formsRepository;
private $finishersRepository;
public function __construct($formsRepository = null, $finishersRepository = null)
{
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
}
public function handle($formId, string $rawData): array
{
$formId = filter_var($formId, FILTER_VALIDATE_INT);
if ($formId === false || $formId < 1) {
return $this->failure(400, ['A valid form id is required.']);
}
try {
$form = $this->formsRepository->findWithId($formId);
} catch (\Throwable $exception) {
return $this->failure(500, ['The form could not be loaded.']);
}
if (!$form) {
return $this->failure(404, ['The requested form was not found.']);
}
$form = (array) $form;
$payload = json_decode($rawData, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($payload) || !isset($payload['fields']) || !is_array($payload['fields'])) {
return $this->failure(400, ['The submission payload is invalid.']);
}
foreach (array_keys($payload) as $key) {
if ($key !== 'fields') {
return $this->failure(400, ['The submission payload contains unsupported data.']);
}
}
$formFields = json_decode($form['fields'] ?? '', true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($formFields) || !$this->isList($formFields)) {
return $this->failure(422, ['The form fields configuration is invalid.']);
}
$fieldErrors = $this->validateFormFields($formFields, $payload['fields']);
if ($fieldErrors) {
return $this->failure(422, $fieldErrors);
}
$finisherEntries = json_decode($form['finishers'] ?? '', true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($finisherEntries) || !$this->isList($finisherEntries)) {
return $this->failure(422, ['The form actions configuration is invalid.']);
}
$configuredFinishers = [];
foreach ($finisherEntries as $entry) {
if (!is_array($entry) || !isset($entry['type']) || !is_string($entry['type']) || $entry['type'] === '') {
return $this->failure(422, ['The form contains an invalid action entry.']);
}
foreach (array_keys($entry) as $key) {
if ($key !== 'type' && $key !== 'options') {
return $this->failure(422, ['The form contains unsupported action settings.']);
}
}
$options = array_key_exists('options', $entry) ? $entry['options'] : [];
if (!is_array($options) || !$this->finishersRepository->finisherExists($entry['type'])) {
return $this->failure(422, ['The form contains an unknown or invalid action.']);
}
$config = $this->finishersRepository->getFinisherConfig($entry['type']);
$class = $config['class'] ?? null;
if (!is_string($class) || !is_subclass_of($class, DefaultFinisher::class)) {
return $this->failure(422, ['The form contains an invalid action configuration.']);
}
$configuredFinishers[] = [
'type' => $entry['type'],
'class' => $class,
'options' => $options,
];
}
$form['formFields'] = $formFields;
$context = [
'formId' => $formId,
'form' => $form,
'rawData' => $rawData,
'submission' => $payload,
];
$actions = [];
foreach ($configuredFinishers as $finisher) {
$success = false;
try {
$instance = new $finisher['class']($context, $finisher['options']);
$success = $instance->execute() === true;
} catch (\Throwable $exception) {
$success = false;
}
$actions[] = [
'type' => $finisher['type'],
'success' => $success,
];
}
$success = !in_array(false, array_column($actions, 'success'), true);
$body = [
'success' => $success,
'actions' => $actions,
'errors' => $success ? [] : ['One or more actions could not be completed.'],
];
return [
'status' => $success ? 200 : 500,
'body' => $body,
];
}
private function validateFormFields(array $formFields, array $submittedFields): array
{
$errors = [];
$knownFields = [];
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
foreach ($formFields as $field) {
if (!is_array($field) || !isset($field['name']) || !is_string($field['name']) || trim($field['name']) === '' || !isset($field['label']) || !is_string($field['label']) || !isset($field['type']) || !is_string($field['type']) || !in_array($field['type'], $supportedTypes, true)) {
return ['The form contains an invalid field configuration.'];
}
$name = $field['name'];
if (array_key_exists($name, $knownFields)) {
return ['The form contains duplicate field names.'];
}
if (array_key_exists('required', $field) && !is_bool($field['required'])) {
return ['The form contains an invalid required-field setting.'];
}
$options = array_key_exists('options', $field) ? $field['options'] : [];
if (!is_array($options) || !$this->isList($options)) {
return ['The form contains invalid field options.'];
}
$optionValues = [];
foreach ($options as $option) {
if (!is_array($option) || !isset($option['label']) || !is_string($option['label']) || !isset($option['value']) || !is_scalar($option['value'])) {
return ['The form contains invalid field options.'];
}
$optionValues[] = (string) $option['value'];
}
$knownFields[$name] = [
'type' => $field['type'],
'required' => $field['required'] ?? false,
'options' => $optionValues,
];
}
foreach (array_keys($submittedFields) as $name) {
if (!is_string($name) || !array_key_exists($name, $knownFields)) {
return ['The submission contains an unknown field.'];
}
}
foreach ($knownFields as $name => $field) {
$value = $submittedFields[$name] ?? null;
$empty = $value === null || $value === false || (is_string($value) && trim($value) === '') || (is_array($value) && count($value) === 0);
if ($field['required'] && $empty) {
$errors[] = 'A value is required for ' . $name . '.';
continue;
}
if ($empty) {
continue;
}
if ($field['type'] === 'checkbox') {
$values = is_array($value) ? $value : [$value];
foreach ($values as $selectedValue) {
if (!is_string($selectedValue) && !is_int($selectedValue)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
break;
}
if (!in_array((string) $selectedValue, $field['options'], true)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
break;
}
}
continue;
}
if (!is_string($value) && !is_int($value) && !is_float($value)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
continue;
}
if (($field['type'] === 'select' || $field['type'] === 'radio') && !in_array((string) $value, $field['options'], true)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
}
if ($field['type'] === 'email' && filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'The email value for ' . $name . ' is invalid.';
}
}
return $errors;
}
private function failure(int $status, array $errors): array
{
return [
'status' => $status,
'body' => [
'success' => false,
'actions' => [],
'errors' => $errors,
],
];
}
private function isList(array $values): bool
{
return $values === [] || array_keys($values) === range(0, count($values) - 1);
}
}
@@ -70,6 +70,23 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
if (type === 'radio') return 'Radio options (single selection)';
return 'Options';
},
setFinisherType(finisher, type) {
finisher.type = type;
if (type === 'sendConfirmationEmailToSubmitter' && (!finisher.options || typeof finisher.options !== 'object' || Array.isArray(finisher.options))) {
finisher.options = {
recipientField: '',
subject: 'Thank you for your submission',
message: 'Thank you for contacting us. We have received your message.'
};
}
},
init() {
this.finishers.forEach(finisher => {
if (finisher.type === 'sendConfirmationEmailToSubmitter') {
this.setFinisherType(finisher, finisher.type);
}
});
},
moveField(fromIndex, toIndex) {
if (toIndex < 0 || toIndex >= this.fields.length) return;
const field = this.fields.splice(fromIndex, 1)[0];
@@ -230,15 +247,38 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<div x-show="finishers.length > 0" class="space-y-2">
<template x-for="(finisher, index) in finishers">
<div class="flex items-center gap-3 p-3 border border-base-300 rounded-lg bg-base-200/50">
<span class="text-xs font-mono text-base-content/40">#[<span x-text="index + 1"></span>]</span>
<select x-model="finisher.type" class="select select-bordered select-sm flex-1">
<option value="saveToDatabase">Save to database</option>
<option value="sendMailToAdmin">Send email to admin</option>
</select>
<button @click="finishers.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove">
<i class="ph-duotone ph-trash"></i>
</button>
<div class="p-3 border border-base-300 rounded-lg bg-base-200/50 space-y-3">
<div class="flex items-center gap-3">
<span class="text-xs font-mono text-base-content/40">#[<span x-text="index + 1"></span>]</span>
<select :value="finisher.type" @change="setFinisherType(finisher, $event.target.value)" class="select select-bordered select-sm flex-1">
<option value="saveToDatabase">Save to database</option>
<option value="sendMailToAdmin">Send email to admin</option>
<option value="sendConfirmationEmailToSubmitter">Send confirmation email to submitter</option>
</select>
<button @click="finishers.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove">
<i class="ph-duotone ph-trash"></i>
</button>
</div>
<div x-show="finisher.type === 'sendConfirmationEmailToSubmitter'" class="space-y-3 pl-8">
<div class="form-control">
<label class="label"><span class="label-text">Recipient email field</span></label>
<select x-model="finisher.options.recipientField" class="select select-bordered select-sm w-full">
<option value="">Select an email field</option>
<template x-for="field in fields.filter(field => field.type === 'email')" :key="field.name">
<option :value="field.name" x-text="field.label + ' (' + field.name + ')' "></option>
</template>
</select>
<span x-show="fields.filter(field => field.type === 'email').length === 0" class="label-text-alt text-warning mt-1">Add an email field to the form before using this action.</span>
</div>
<div class="form-control">
<label class="label"><span class="label-text">Subject</span></label>
<input type="text" x-model="finisher.options.subject" class="input input-bordered input-sm w-full" />
</div>
<div class="form-control">
<label class="label"><span class="label-text">Message</span></label>
<textarea x-model="finisher.options.message" class="textarea textarea-bordered w-full" rows="4"></textarea>
</div>
</div>
</div>
</template>
</div>
@@ -8,16 +8,26 @@ if ($id > 0):
?>
<div class="max-w-2xl mx-auto">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false}">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false, errorMessage: ''}">
<form x-show="!submitted" x-transition:leave x-transition:leave-opacity-0 x-on:submit.prevent="
status = 'busy';
fetch('/ext--form/submit?id=<?= $id ?>', {
method: 'POST',
body: JSON.stringify(data)
}).finally(() => {
status = 'idle';
errorMessage = '';
try {
const response = await fetch('/ext--form/submit?id=<?= $id ?>', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
const result = await response.json();
if (!response.ok || !result.success) {
throw new Error((result.errors || []).join(' ') || 'Your submission could not be completed. Please try again.');
}
submitted = true;
})
} catch (error) {
errorMessage = error.message || 'Your submission could not be completed. Please try again.';
} finally {
status = 'idle';
}
">
<?php foreach ($fields as $field):
@@ -101,6 +111,7 @@ if ($id > 0):
</button>
</div>
</form>
<div x-show="errorMessage" x-text="errorMessage" class="alert alert-error mt-4" role="alert"></div>
<div x-show="submitted" x-transition:enter x-transition:enter-opacity-0 x-transition:enter-delay-100 class="card bg-base-100 shadow-lg mt-4">
<div class="card-body items-center text-center">
<div class="w-16 h-16 rounded-full bg-success/20 flex items-center justify-center mb-2">
+5 -17
View File
@@ -1,22 +1,10 @@
<?php
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
$result = $handler->handle($_GET['id'] ?? null, file_get_contents('php://input') ?: '');
$form = $formsRepository->findWithId($_GET['id']);
$formFinishers = json_decode($form['finishers'], true);
$finishers = new \Plugi\Extensions\Form\Finishers\FinishersRepository();
foreach ($formFinishers as $finisher) {
if ($finishers->finisherExists($finisher['type'])) {
$config = $finishers->getFinisherConfig($finisher['type']);
$instance = new $config['class'];
$instance->execute();
}
}
phpb_redirect('/', [], 201);
http_response_code($result['status']);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result['body'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
@@ -0,0 +1,219 @@
<?php
namespace FormExtensionTests {
require_once dirname(__DIR__) . '/admin/Classes/Finishers/DefaultFinisher.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
class TestConfirmationFinisher extends \Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter
{
protected function sendMail(string $recipient, string $subject, string $message): bool
{
$GLOBALS['confirmationEmails'][] = [$recipient, $subject, $message];
return true;
}
}
class FirstFinisher extends \Plugi\Extensions\Form\Finishers\DefaultFinisher
{
public function execute(): bool
{
if ($this->formId !== 7 || $this->getFormName() !== 'Contact form' || $this->getEntryFields()['name'] !== 'Ada' || ($this->options['marker'] ?? null) !== 'passed') {
throw new \RuntimeException('The submission context or action options were not passed to the finisher.');
}
$GLOBALS['formFinisherCalls'][] = 'first';
return $GLOBALS['formFinisherResults']['first'];
}
}
class SecondFinisher extends \Plugi\Extensions\Form\Finishers\DefaultFinisher
{
public function execute(): bool
{
$GLOBALS['formFinisherCalls'][] = 'second';
return $GLOBALS['formFinisherResults']['second'];
}
}
class DefinitionsRepository
{
private $form;
public function __construct($form)
{
$this->form = $form;
}
public function findWithId($id)
{
return $this->form;
}
}
class FinishersRepository
{
private $finishers = [
'first' => FirstFinisher::class,
'second' => SecondFinisher::class,
'sendConfirmationEmailToSubmitter' => TestConfirmationFinisher::class,
];
public function finisherExists(string $key): bool
{
return isset($this->finishers[$key]);
}
public function getFinisherConfig(string $key): array
{
return ['class' => $this->finishers[$key]];
}
}
}
namespace {
require_once dirname(__DIR__) . '/admin/Classes/SubmissionHandler.php';
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
use Plugi\Extensions\Form\SubmissionHandler;
function assertSameValue($expected, $actual, string $message): void
{
if ($expected !== $actual) {
throw new \RuntimeException($message . ': expected ' . var_export($expected, true) . ', got ' . var_export($actual, true));
}
}
function makeHandler($form): SubmissionHandler
{
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository());
}
function validForm(array $finishers = []): array
{
return [
'name' => 'Contact form',
'fields' => json_encode([
['name' => 'name', 'label' => 'Name', 'type' => 'text', 'required' => true],
]),
'finishers' => json_encode($finishers),
];
}
$form = validForm([
['type' => 'first', 'options' => ['marker' => 'passed']],
['type' => 'second'],
]);
$validPayload = json_encode(['fields' => ['name' => 'Ada']]);
$GLOBALS['formFinisherCalls'] = [];
$GLOBALS['formFinisherResults'] = ['first' => true, 'second' => true];
$result = makeHandler($form)->handle(7, $validPayload);
assertSameValue(200, $result['status'], 'Successful actions must produce a successful response');
assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order');
$GLOBALS['formFinisherCalls'] = [];
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
$result = makeHandler($form)->handle(7, $validPayload);
assertSameValue(500, $result['status'], 'A failed action must fail the submission');
assertSameValue(false, $result['body']['success'], 'A failed action must not report success');
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order after a failure');
assertSameValue([false, true], array_column($result['body']['actions'], 'success'), 'Each action result must be reported');
$GLOBALS['formFinisherCalls'] = [];
$result = makeHandler($form)->handle(7, '{invalid');
assertSameValue(400, $result['status'], 'Malformed JSON must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Malformed requests must not run actions');
$result = makeHandler($form)->handle(7, json_encode(['fields' => []]));
assertSameValue(422, $result['status'], 'Missing required values must be rejected');
$invalidForm = validForm();
$invalidForm['fields'] = '{invalid';
$result = makeHandler($invalidForm)->handle(7, $validPayload);
assertSameValue(422, $result['status'], 'Malformed form configuration must be rejected');
$result = makeHandler(null)->handle(7, $validPayload);
assertSameValue(404, $result['status'], 'Missing forms must be rejected');
$unknownForm = validForm([['type' => 'unknown']]);
$result = makeHandler($unknownForm)->handle(7, $validPayload);
assertSameValue(422, $result['status'], 'Unknown actions must be rejected');
$malformedOptionsForm = validForm([['type' => 'first', 'options' => 'invalid']]);
$result = makeHandler($malformedOptionsForm)->handle(7, $validPayload);
assertSameValue(422, $result['status'], 'Malformed action options must be rejected');
$view = file_get_contents(dirname(__DIR__) . '/blocks/form-wrapper/view.php');
if (strpos($view, '!response.ok || !result.success') === false || strpos($view, 'x-show="errorMessage"') === false) {
throw new \RuntimeException('The frontend must check the response and expose a retryable error state.');
}
if (preg_match('/if \(!response\.ok \|\| !result\.success\).*?submitted = true;/s', $view) !== 1) {
throw new \RuntimeException('The frontend may only show its success state after a successful response.');
}
$editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php');
foreach (['finisher.options.recipientField', 'finisher.options.subject', 'finisher.options.message'] as $setting) {
if (strpos($editor, $setting) === false) {
throw new \RuntimeException('The action editor is missing a confirmation setting: ' . $setting);
}
}
$finisherConfig = require dirname(__DIR__) . '/admin/Classes/Finishers/config.php';
assertSameValue(
\Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter::class,
$finisherConfig['finishers']['sendConfirmationEmailToSubmitter']['class'],
'The confirmation finisher must be registered'
);
$confirmationContext = [
'formId' => 8,
'form' => [
'name' => 'Contact form',
'formFields' => [['name' => 'email', 'label' => 'Email', 'type' => 'email']],
],
'rawData' => json_encode(['fields' => ['email' => 'ada@example.com']]),
'submission' => ['fields' => ['email' => 'ada@example.com']],
];
$confirmationOptions = [
'recipientField' => 'email',
'subject' => 'We received your message',
'message' => 'Thanks, Ada.',
];
$GLOBALS['confirmationEmails'] = [];
$confirmationFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $confirmationOptions);
assertSameValue(true, $confirmationFinisher->execute(), 'A valid recipient should be sent a confirmation');
assertSameValue(
[['ada@example.com', 'We received your message', 'Thanks, Ada.']],
$GLOBALS['confirmationEmails'],
'The configured recipient, subject, and message must be sent'
);
$invalidRecipientContext = $confirmationContext;
$invalidRecipientContext['submission']['fields']['email'] = 'not-an-email';
$invalidRecipientFinisher = new \FormExtensionTests\TestConfirmationFinisher($invalidRecipientContext, $confirmationOptions);
assertSameValue(false, $invalidRecipientFinisher->execute(), 'An invalid recipient must fail');
assertSameValue(1, count($GLOBALS['confirmationEmails']), 'An invalid recipient must not send email');
$staleFieldOptions = $confirmationOptions;
$staleFieldOptions['recipientField'] = 'removed_email';
$staleFieldFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $staleFieldOptions);
assertSameValue(false, $staleFieldFinisher->execute(), 'A stale recipient field selection must fail');
assertSameValue(1, count($GLOBALS['confirmationEmails']), 'A stale field selection must not send email');
$confirmationForm = [
'name' => 'Contact form',
'fields' => json_encode([['name' => 'email', 'label' => 'Email', 'type' => 'email']]),
'finishers' => json_encode([[
'type' => 'sendConfirmationEmailToSubmitter',
'options' => $confirmationOptions,
]]),
];
$GLOBALS['confirmationEmails'] = [];
$result = makeHandler($confirmationForm)->handle(8, json_encode(['fields' => ['email' => 'ada@example.com']]));
assertSameValue(true, $result['body']['success'], 'A valid confirmation action must report success');
$result = makeHandler($confirmationForm)->handle(8, json_encode(['fields' => ['email' => '']]));
assertSameValue(500, $result['status'], 'A missing optional recipient must report action failure');
assertSameValue(false, $result['body']['actions'][0]['success'], 'A missing recipient must not report action success');
echo "Submission handler checks passed.\n";
}