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.
This commit is contained in:
2026-11-24 18:51:20 +01:00
parent dfe1e40e58
commit d5597b045f
6 changed files with 459 additions and 42 deletions
@@ -4,6 +4,8 @@ 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
{
@@ -26,6 +28,83 @@ namespace FormExtensionTests {
}
}
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
@@ -68,6 +147,7 @@ namespace FormExtensionTests {
'first' => FirstFinisher::class,
'second' => SecondFinisher::class,
'sendConfirmationEmailToSubmitter' => TestConfirmationFinisher::class,
'sendWebhook' => TestWebhookFinisher::class,
];
public function finisherExists(string $key): bool
@@ -184,9 +264,9 @@ namespace {
}
$editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php');
foreach (['finisher.options.recipientField', 'finisher.options.subject', 'finisher.options.message'] as $setting) {
foreach (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) {
if (strpos($editor, $setting) === false) {
throw new \RuntimeException('The action editor is missing a confirmation setting: ' . $setting);
throw new \RuntimeException('The action editor is missing registry-driven setting support: ' . $setting);
}
}
@@ -196,6 +276,24 @@ namespace {
$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,
@@ -239,6 +337,79 @@ namespace {
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);
@@ -278,6 +449,18 @@ namespace {
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']]),