added ability to convert the response body

pull/571/head
Austin Collier 10 months ago
parent 4d79dea91b
commit 7fca8d9a45

@ -128,6 +128,13 @@ class Response
*/ */
protected bool $sent = false; protected bool $sent = false;
/**
* These are callbacks that can process the response body before it's sent
*
* @var array<int, callable> $responseBodyCallbacks
*/
protected array $responseBodyCallbacks = [];
/** /**
* Sets the HTTP status of the response. * Sets the HTTP status of the response.
* *
@ -429,8 +436,37 @@ class Response
$this->sendHeaders(); // @codeCoverageIgnore $this->sendHeaders(); // @codeCoverageIgnore
} }
// Only for the v3 output buffering.
if($this->v2_output_buffering === false) {
$this->processResponseCallbacks();
}
echo $this->body; echo $this->body;
$this->sent = true; $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);
}
}
} }

@ -255,4 +255,37 @@ class ResponseTest extends TestCase
$response->write('new', true); $response->write('new', true);
$this->assertEquals('new', $response->getBody()); $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);
}
} }

Loading…
Cancel
Save