Files
plugi/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php
T
deepDiverPaul d5597b045f add configurable form finishers and webhook delivery
Expose finisher settings through the editor registry and build the action editor dynamically. Add configurable admin email recipients and subjects, and introduce a webhook finisher with validated request options and JSON submission payloads.

Expand submission handler tests to cover editor configuration, email overrides, webhook validation, HTTP responses, and submission outcomes.
2026-11-24 18:51:20 +01:00

481 lines
22 KiB
PHP

<?php
namespace FormExtensionTests {
require_once dirname(__DIR__) . '/admin/Classes/Finishers/DefaultFinisher.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendEmailToAdmin.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/FinishersRepository.php';
class TestMailer
{
public $calls = [];
public $result = true;
public function send(string $to, string $subject, string $message): bool
{
$this->calls[] = [$to, $subject, $message];
return $this->result;
}
}
class TestConfirmationFinisher extends \Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter
{
protected function sendMail(string $recipient, string $subject, string $message): bool
{
$GLOBALS['confirmationEmails'][] = [$recipient, $subject, $message];
return parent::sendMail($recipient, $subject, $message);
}
}
class TestWebhookFinisher extends \Plugi\Extensions\Form\Finishers\SendWebhook
{
protected function sendRequest(string $url, string $method, ?string $bearerToken, string $payload, int $timeout): ?int
{
$GLOBALS['webhookRequests'][] = [
$url,
$method,
$bearerToken,
json_decode($payload, true),
$timeout,
];
return $GLOBALS['webhookResponseCode'] ?? null;
}
}
function startWebhookPeer(int $responseCode): array
{
$server = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($server)) {
throw new \RuntimeException('Could not start the local webhook test peer.');
}
$address = stream_socket_get_name($server, false);
$port = (int) substr(strrchr($address, ':'), 1);
$pid = pcntl_fork();
if ($pid === -1) {
fclose($server);
throw new \RuntimeException('Could not start the local webhook test peer process.');
}
if ($pid === 0) {
$client = stream_socket_accept($server, 5);
fclose($server);
if (!is_resource($client)) {
exit(1);
}
stream_set_timeout($client, 5);
$requestLine = fgets($client, 2048);
$headers = [];
while (($line = fgets($client, 2048)) !== false && $line !== "\r\n") {
$header = explode(':', trim($line), 2);
if (count($header) === 2) {
$headers[strtolower($header[0])] = trim($header[1]);
}
}
$contentLength = (int) ($headers['content-length'] ?? 0);
$body = '';
while (strlen($body) < $contentLength) {
$chunk = fread($client, $contentLength - strlen($body));
if (!is_string($chunk) || $chunk === '') {
break;
}
$body .= $chunk;
}
$payload = json_decode($body, true);
$passed = $requestLine === "POST /receive HTTP/1.1\r\n"
&& ($headers['content-type'] ?? '') === 'application/json'
&& ($headers['authorization'] ?? '') === 'Bearer peer-token'
&& is_array($payload)
&& ($payload['formId'] ?? null) === 8
&& ($payload['formName'] ?? null) === 'Contact form'
&& ($payload['fields']['name'] ?? null) === 'Ada'
&& strlen($body) === $contentLength;
$reason = $responseCode === 202 ? 'Accepted' : 'Service Unavailable';
fwrite($client, 'HTTP/1.1 ' . $responseCode . ' ' . $reason . "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
fclose($client);
exit($passed ? 0 : 1);
}
fclose($server);
return [$port, $pid];
}
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,
'sendWebhook' => TestWebhookFinisher::class,
];
public function finisherExists(string $key): bool
{
return isset($this->finishers[$key]);
}
public function getFinisherConfig(string $key): array
{
return ['class' => $this->finishers[$key]];
}
}
}
namespace Plugi {
class Extensions
{
public static function getSettings(string $name): array
{
return $GLOBALS['extensionSettings'][$name] ?? [];
}
}
}
namespace {
require_once dirname(__DIR__) . '/admin/Classes/SubmissionHandler.php';
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
use Plugi\Extensions\Form\SubmissionHandler;
if (!function_exists('phpb_instance')) {
function phpb_instance(string $name, array $params = []): ?object
{
return $name === 'mail' ? ($GLOBALS['testMailer'] ?? null) : null;
}
}
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),
];
}
$GLOBALS['testMailer'] = new \FormExtensionTests\TestMailer();
$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 (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) {
if (strpos($editor, $setting) === false) {
throw new \RuntimeException('The action editor is missing registry-driven setting support: ' . $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'
);
assertSameValue(
\Plugi\Extensions\Form\Finishers\SendWebhook::class,
$finisherConfig['finishers']['sendWebhook']['class'],
'The webhook finisher must be registered'
);
assertSameValue(
['url', 'method', 'bearerToken', 'timeout'],
array_column($finisherConfig['finishers']['sendWebhook']['settings'], 'name'),
'Webhook settings must be exposed to the editor'
);
assertSameValue(
['recipient', 'subject'],
array_column($finisherConfig['finishers']['sendMailToAdmin']['settings'], 'name'),
'Admin notification settings must be exposed to the editor'
);
$editorFinisherConfig = (new \Plugi\Extensions\Form\Finishers\FinishersRepository())->getEditorConfig();
assertSameValue('Send webhook', $editorFinisherConfig['sendWebhook']['label'], 'The editor registry must expose the webhook label');
assertSameValue(false, array_key_exists('class', $editorFinisherConfig['sendWebhook']), 'The editor registry must not expose runtime class names');
$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'] = [];
$GLOBALS['testMailer']->calls = [];
$GLOBALS['testMailer']->result = true;
$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'
);
assertSameValue(
[['ada@example.com', 'We received your message', 'Thanks, Ada.']],
$GLOBALS['testMailer']->calls,
'The confirmation finisher must use the configured core mailer'
);
$GLOBALS['testMailer']->result = false;
$failedConfirmationFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $confirmationOptions);
assertSameValue(false, $failedConfirmationFinisher->execute(), 'A failed core mail send must fail the confirmation action');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'The failed confirmation must be sent through the core mailer');
$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(2, count($GLOBALS['confirmationEmails']), 'An invalid recipient must not send email');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'An invalid recipient must not call the core mailer');
$webhookContext = [
'formId' => 8,
'form' => [
'name' => 'Contact form',
'formFields' => [['name' => 'name', 'label' => 'Name', 'type' => 'text']],
],
'submission' => ['fields' => ['name' => 'Ada']],
];
$webhookOptions = [
'url' => 'https://hooks.example.test/receive',
'method' => 'POST',
'bearerToken' => 'test-secret',
'timeout' => 8,
];
$GLOBALS['webhookRequests'] = [];
$GLOBALS['webhookResponseCode'] = 204;
$webhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $webhookOptions);
assertSameValue(true, $webhookFinisher->execute(), 'A successful webhook response must succeed');
assertSameValue(
[[
'https://hooks.example.test/receive',
'POST',
'test-secret',
['formId' => 8, 'formName' => 'Contact form', 'fields' => ['name' => 'Ada']],
8,
]],
$GLOBALS['webhookRequests'],
'The webhook must receive configured request options and the submission payload'
);
$GLOBALS['webhookResponseCode'] = 503;
$failedWebhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $webhookOptions);
assertSameValue(false, $failedWebhookFinisher->execute(), 'A non-success webhook response must fail');
$invalidWebhookOptions = $webhookOptions;
$invalidWebhookOptions['url'] = 'file:///etc/passwd';
$invalidWebhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $invalidWebhookOptions);
assertSameValue(false, $invalidWebhookFinisher->execute(), 'An unsupported webhook URL scheme must fail');
assertSameValue(2, count($GLOBALS['webhookRequests']), 'Invalid webhook options must not make a request');
$invalidWebhookOptions = $webhookOptions;
$invalidWebhookOptions['bearerToken'] = "token\r\nInjected: true";
$invalidWebhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $invalidWebhookOptions);
assertSameValue(false, $invalidWebhookFinisher->execute(), 'Webhook bearer tokens must reject header injection');
assertSameValue(2, count($GLOBALS['webhookRequests']), 'Unsafe webhook credentials must not make a request');
[$webhookPort, $webhookPid] = \FormExtensionTests\startWebhookPeer(202);
$liveWebhookOptions = [
'url' => 'http://127.0.0.1:' . $webhookPort . '/receive',
'method' => 'POST',
'bearerToken' => 'peer-token',
'timeout' => 3,
];
$liveWebhookFinisher = new \Plugi\Extensions\Form\Finishers\SendWebhook($webhookContext, $liveWebhookOptions);
assertSameValue(true, $liveWebhookFinisher->execute(), 'A real 2xx webhook response must succeed');
pcntl_waitpid($webhookPid, $webhookStatus);
assertSameValue(true, pcntl_wifexited($webhookStatus) && pcntl_wexitstatus($webhookStatus) === 0, 'The webhook peer must receive the expected request');
[$webhookPort, $webhookPid] = \FormExtensionTests\startWebhookPeer(503);
$liveWebhookOptions['url'] = 'http://127.0.0.1:' . $webhookPort . '/receive';
$failedLiveWebhookFinisher = new \Plugi\Extensions\Form\Finishers\SendWebhook($webhookContext, $liveWebhookOptions);
assertSameValue(false, $failedLiveWebhookFinisher->execute(), 'A real non-2xx webhook response must fail');
pcntl_waitpid($webhookPid, $webhookStatus);
assertSameValue(true, pcntl_wifexited($webhookStatus) && pcntl_wexitstatus($webhookStatus) === 0, 'The failing-response peer must still receive the expected request');
$webhookForm = validForm([['type' => 'sendWebhook', 'options' => $webhookOptions]]);
$GLOBALS['webhookResponseCode'] = 202;
$result = makeHandler($webhookForm)->handle(8, $validPayload);
assertSameValue(true, $result['body']['success'], 'A successful webhook action must report success');
$GLOBALS['webhookResponseCode'] = 500;
$result = makeHandler($webhookForm)->handle(8, $validPayload);
assertSameValue(500, $result['status'], 'A failed webhook action must fail the submission');
assertSameValue(false, $result['body']['actions'][0]['success'], 'A failed webhook must not report action success');
$staleFieldOptions = $confirmationOptions;
$staleFieldOptions['recipientField'] = 'removed_email';
$staleFieldFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $staleFieldOptions);
assertSameValue(false, $staleFieldFinisher->execute(), 'A stale recipient field selection must fail');
assertSameValue(2, count($GLOBALS['confirmationEmails']), 'A stale field selection must not send email');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'A stale field selection must not call the core mailer');
$GLOBALS['extensionSettings']['form'] = ['email' => ['value' => 'admin@example.com']];
$adminContext = [
'formId' => 8,
'form' => [
'name' => 'Contact form',
'formFields' => [
['name' => 'name', 'label' => 'Name', 'type' => 'text'],
['name' => 'email', 'label' => 'Email', 'type' => 'email'],
],
],
'submission' => ['fields' => ['name' => 'Ada', 'email' => 'ada@example.com']],
];
$GLOBALS['testMailer']->calls = [];
$GLOBALS['testMailer']->result = true;
$adminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext);
assertSameValue(true, $adminFinisher->execute(), 'A successful core mail send must succeed for admin notifications');
assertSameValue(
[['admin@example.com', 'Form submission: Contact form', "Name: Ada\nEmail: ada@example.com\n"]],
$GLOBALS['testMailer']->calls,
'The admin finisher must preserve message composition and use the core mailer'
);
$GLOBALS['testMailer']->result = false;
$failedAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext);
assertSameValue(false, $failedAdminFinisher->execute(), 'A failed core mail send must fail the admin notification action');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'The failed admin notification must be sent through the core mailer');
$GLOBALS['extensionSettings']['form']['email']['value'] = 'invalid-address';
$invalidAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext);
assertSameValue(false, $invalidAdminFinisher->execute(), 'An invalid admin recipient must fail');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'An invalid admin recipient must not call the core mailer');
$GLOBALS['testMailer']->result = true;
$configuredAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext, [
'recipient' => 'configured@example.com',
'subject' => 'New submission',
]);
assertSameValue(true, $configuredAdminFinisher->execute(), 'Per-form admin email settings must override extension defaults');
assertSameValue(
['configured@example.com', 'New submission', "Name: Ada\nEmail: ada@example.com\n"],
$GLOBALS['testMailer']->calls[2],
'The admin finisher must use its configured recipient and subject'
);
$confirmationForm = [
'name' => 'Contact form',
'fields' => json_encode([['name' => 'email', 'label' => 'Email', 'type' => 'email']]),
'finishers' => json_encode([[
'type' => 'sendConfirmationEmailToSubmitter',
'options' => $confirmationOptions,
]]),
];
$GLOBALS['confirmationEmails'] = [];
$GLOBALS['testMailer']->result = true;
$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";
}