Files
plugi/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php
T
deepDiverPaul 25030638a4 Implemented: editor uploads are constrained to safe image files inside
the upload tree, and public form submissions are
size-bounded and rate-limited
2026-11-30 16:51:15 +01:00

581 lines
27 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';
require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.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]];
}
}
class RateLimitDatabase
{
public array $rows = [];
public function query(string $query, array $parameters = []): bool
{
if (str_starts_with($query, 'INSERT IGNORE')) {
$key = $parameters[0] . ':' . $parameters[1];
$this->rows[$key] ??= ['startedAt' => $parameters[2], 'submissions' => 0];
return true;
}
if (str_starts_with($query, 'UPDATE')) {
$key = $parameters[2] . ':' . $parameters[3];
$this->rows[$key] = ['startedAt' => $parameters[0], 'submissions' => $parameters[1]];
return true;
}
if (str_starts_with($query, 'DELETE')) {
return true;
}
throw new \RuntimeException('Unexpected rate limiter query.');
}
public function select(string $query, array $parameters): array
{
$key = $parameters[0] . ':' . $parameters[1];
return isset($this->rows[$key]) ? [$this->rows[$key]] : [];
}
public function transaction(callable $callback): mixed
{
return $callback();
}
}
}
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 FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase;
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, $rateLimiter = null): SubmissionHandler
{
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository(), $rateLimiter ?? new AllowSubmissionRateLimiter());
}
class AllowSubmissionRateLimiter
{
public function consume(int $formId, string $clientIp): bool
{
return true;
}
}
class RejectSubmissionRateLimiter
{
public function consume(int $formId, string $clientIp): bool
{
return false;
}
}
$rateLimitDatabase = new TestRateLimitDatabase();
$rateLimiter = new \Plugi\Extensions\Form\SubmissionRateLimiter($rateLimitDatabase);
for ($submission = 0; $submission < 5; $submission++) {
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions within the limit must be allowed.');
}
assertSameValue(false, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions over the limit must be rejected.');
assertSameValue(true, $rateLimiter->consume(8, '203.0.113.1'), 'Rate limits must be scoped to each form.');
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.2'), 'Rate limits must be scoped to each client IP.');
$rateLimitKey = '7:' . hash('sha256', '203.0.113.1');
$rateLimitDatabase->rows[$rateLimitKey]['startedAt'] = time() - 601;
$rateLimitDatabase->rows[$rateLimitKey]['submissions'] = 5;
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Expired rate limit windows must reset.');
assertSameValue(1, $rateLimitDatabase->rows[$rateLimitKey]['submissions'], 'The reset window must begin at one submission.');
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'] = [];
$result = makeHandler($form, new RejectSubmissionRateLimiter())->handle(7, $validPayload);
assertSameValue(429, $result['status'], 'Rate-limited submissions must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Rate-limited submissions must not run actions');
$GLOBALS['formFinisherCalls'] = [];
$result = makeHandler($form)->handle(7, str_repeat('x', 65537));
assertSameValue(413, $result['status'], 'Oversized request bodies must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized requests must not run actions');
$GLOBALS['formFinisherCalls'] = [];
$oversizedField = json_encode(['fields' => ['name' => str_repeat('A', 16385)]]);
$result = makeHandler($form)->handle(7, $oversizedField);
assertSameValue(422, $result['status'], 'Oversized field values must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized fields must not run actions');
$tooManyFields = array_fill_keys(array_map('strval', range(1, 101)), 'value');
$result = makeHandler($form)->handle(7, json_encode(['fields' => $tooManyFields]));
assertSameValue(422, $result['status'], 'Submissions with too many fields must be rejected');
$submitRoute = file_get_contents(dirname(__DIR__) . '/routes/submit.php');
if (strpos($submitRoute, 'MAX_REQUEST_BYTES + 1') === false) {
throw new \RuntimeException('The submission route must read no more than the configured body limit plus one byte.');
}
$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');
$frontendScript = file_get_contents(dirname(__DIR__) . '/assets/main.js');
if (strpos($view, 'data-form-wrapper') === false || preg_match('/\bx-(?:data|model|show|on|transition|text)\b/', $view) === 1) {
throw new \RuntimeException('The public form wrapper must use vanilla JavaScript hooks without Alpine directives.');
}
if (strpos($frontendScript, 'if (!response.ok || !result || !result.success)') === false || strpos($frontendScript, 'setVisible(errorMessage, true)') === false) {
throw new \RuntimeException('The frontend must check the response and expose a retryable error state.');
}
$responseCheck = strpos($frontendScript, 'if (!response.ok || !result || !result.success)');
$successState = strpos($frontendScript, 'setVisible(successMessage, true)');
if ($successState === false || $responseCheck === false || $responseCheck > $successState) {
throw new \RuntimeException('The frontend may only show its success state after a successful response.');
}
if (strpos($frontendScript, 'finally') === false || strpos($frontendScript, 'setBusy(form, false)') === false) {
throw new \RuntimeException('The frontend must restore its busy state after a submission attempt.');
}
$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";
}