From 7fca8d9a45d5b9d529af767f772ab5c66d9b9dd3 Mon Sep 17 00:00:00 2001 From: Austin Collier Date: Mon, 8 Apr 2024 20:55:12 -0600 Subject: [PATCH] added ability to convert the response body --- flight/net/Response.php | 36 ++++++++++++++++++++++++++++++++++++ tests/ResponseTest.php | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/flight/net/Response.php b/flight/net/Response.php index 2971bd9..9d1c610 100644 --- a/flight/net/Response.php +++ b/flight/net/Response.php @@ -128,6 +128,13 @@ class Response */ protected bool $sent = false; + /** + * These are callbacks that can process the response body before it's sent + * + * @var array $responseBodyCallbacks + */ + protected array $responseBodyCallbacks = []; + /** * Sets the HTTP status of the response. * @@ -429,8 +436,37 @@ class Response $this->sendHeaders(); // @codeCoverageIgnore } + // Only for the v3 output buffering. + if($this->v2_output_buffering === false) { + $this->processResponseCallbacks(); + } + echo $this->body; $this->sent = true; } + + /** + * Adds a callback to process the response body before it's sent. These are processed in the order + * they are added + * + * @param callable $callback The callback to process the response body + * @return void + */ + public function addResponseBodyCallback(callable $callback): void + { + $this->responseBodyCallbacks[] = $callback; + } + + /** + * Cycles through the response body callbacks and processes them in order + * + * @return void + */ + protected function processResponseCallbacks(): void + { + foreach ($this->responseBodyCallbacks as $callback) { + $this->body = $callback($this->body); + } + } } diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php index 42701d4..3226cc9 100644 --- a/tests/ResponseTest.php +++ b/tests/ResponseTest.php @@ -255,4 +255,37 @@ class ResponseTest extends TestCase $response->write('new', true); $this->assertEquals('new', $response->getBody()); } + + public function testResponseBodyCallback() + { + $response = new Response(); + $response->write('test'); + $str_rot13 = function ($body) { + return str_rot13($body); + }; + $response->addResponseBodyCallback($str_rot13); + ob_start(); + $response->send(); + $rot13_body = ob_get_clean(); + $this->assertEquals('grfg', $rot13_body); + } + + public function testResponseBodyCallbackMultiple() + { + $response = new Response(); + $response->write('test'); + $str_rot13 = function ($body) { + return str_rot13($body); + }; + $str_replace = function ($body) { + return str_replace('g', 'G', $body); + }; + $response->addResponseBodyCallback($str_rot13); + $response->addResponseBodyCallback($str_replace); + $response->addResponseBodyCallback($str_rot13); + ob_start(); + $response->send(); + $rot13_body = ob_get_clean(); + $this->assertEquals('TesT', $rot13_body); + } }