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.
219 lines
9.8 KiB
PHP
219 lines
9.8 KiB
PHP
<?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";
|
|
} |