← Back
Editing: Response_Closer.php
<?php declare( strict_types=1 ); namespace Uncanny_Automator\App\Infrastructure\Webhooks; /** * Sends a webhook sender its answer and closes the connection, so the work * that follows in the same request (draining the inbox, running recipes) no * longer holds the sender's delivery open. * * PHP-FPM (`fastcgi_finish_request()`) and LiteSpeed * (`litespeed_finish_request()`) can send the whole response and keep the * request running. Other servers (mod_php, the CLI) have neither: there the * connection stays open until PHP ends, as it always did, and close() reports * that it could not close. * * Call it at `shutdown`, once the answer has been written: the REST server and * the Query_Door both echo their answer before the request ends. The request's * one instance is {@see \Uncanny_Automator\App\Infrastructure\automator_response_closer()}, * shared by the {@see Webhook_Router} (deferred handlers) and the platform * receiver (inbox drain). * * @since 8.1.2 */ final class Response_Closer { /** * The host functions that send the response and keep PHP running, in order of preference. */ private const HOST_FUNCTIONS = array( 'fastcgi_finish_request', 'litespeed_finish_request' ); /** * The host function that closes the response, or null when the host has none. * * @var callable|null */ private $finish = null; /** * Sends what the output buffers still hold, so closing loses none of the answer. * * @var callable */ private $flush; /** * Whether this request's response is already closed. * * @var bool */ private $closed = false; /** * @since 8.1.2 * * @param array<int,mixed>|null $finish_functions The closing functions to try, in order (the host's own by default). * @param callable|null $flush Sends the output buffers (`wp_ob_end_flush_all` by default). */ public function __construct( ?array $finish_functions = null, ?callable $flush = null ) { foreach ( $finish_functions ?? self::HOST_FUNCTIONS as $candidate ) { if ( is_callable( $candidate ) ) { $this->finish = $candidate; break; } } $this->flush = $flush ?? 'wp_ob_end_flush_all'; } /** * Send the answer and close the connection, once per request. * * After the close PHP would end at the next output when the client has * gone, and the recipes that run next may print, so a closed request ignores * the client's abort, as WordPress does before it finishes a cron request. * * @since 8.1.2 * * @return bool Whether the response is closed: false on a host that cannot close it early. */ public function close(): bool { if ( $this->closed ) { return true; } if ( null === $this->finish ) { return false; } ignore_user_abort( true ); ( $this->flush )(); ( $this->finish )(); $this->closed = true; return true; } }
Save File
Cancel