Skip to content

Commit

Permalink
Merge pull request cakephp#17514 from cakephp/5.1-server-terminate
Browse files Browse the repository at this point in the history
Add Server.terminate event.
  • Loading branch information
othercorey authored Jan 12, 2024
2 parents a0029a3 + d89d942 commit 2955123
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Http/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,24 @@ public function emit(ResponseInterface $response, ?ResponseEmitter $emitter = nu
$emitter->emit($response);
}

/**
* Trigger the Server.terminate event.
*
* The event is used to do potentially heavy tasks after the response is sent
* to the client. Only the PHP FPM server API is able to send a response to
* the client while the server's PHP process still performs some tasks. For
* other environments the event will be triggered before the response is flushed
* to the client and will have no benefit.
*
* @param \Psr\Http\Message\ServerRequestInterface $request Request instance.
* @param \Psr\Http\Message\ResponseInterface $response Response instance.
* @return void
*/
public function terminate(ServerRequestInterface $request, ResponseInterface $response): void
{
$this->dispatchEvent('Server.terminate', compact('request', 'response'));
}

/**
* Get the current application.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase/Http/ServerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Cake\Http\BaseApplication;
use Cake\Http\CallbackStream;
use Cake\Http\MiddlewareQueue;
use Cake\Http\Response;
use Cake\Http\ResponseEmitter;
use Cake\Http\Server;
use Cake\Http\ServerRequest;
Expand All @@ -32,6 +33,7 @@
use Laminas\Diactoros\ServerRequest as LaminasServerRequest;
use Mockery;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TestApp\Http\MiddlewareApplication;

require_once __DIR__ . '/server_mocks.php';
Expand Down Expand Up @@ -353,4 +355,23 @@ public function testAppWithoutContainerApplicationInterface(): void
$request = new ServerRequest();
$this->assertInstanceOf(ResponseInterface::class, $server->run($request));
}

public function testTerminate(): void
{
/** @var \Cake\Core\HttpApplicationInterface|\PHPUnit\Framework\MockObject\MockObject $app */
$app = $this->createMock(HttpApplicationInterface::class);
$server = new Server($app);

$triggered = false;
$server->getEventManager()->on(
'Server.terminate',
function (EventInterface $event, ServerRequestInterface $request, ResponseInterface $response) use (&$triggered) {
$triggered = true;
}
);

$server->terminate(new ServerRequest(), new Response());

$this->assertTrue($triggered);
}
}

0 comments on commit 2955123

Please sign in to comment.