Skip to content

Commit c37930b

Browse files
reininkADmad
authored andcommitted
Add the ability to set a callable response body.
1 parent f0d3a7a commit c37930b

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/Network/Response.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ class Response
335335
protected $_headers = [];
336336

337337
/**
338-
* Buffer string for response message
338+
* Buffer string or callable for response message
339339
*
340340
* @var string
341341
*/
@@ -538,13 +538,18 @@ protected function _sendHeader($name, $value = null)
538538

539539
/**
540540
* Sends a content string to the client.
541+
* If the content is a callable, it is invoked.
541542
*
542543
* @param string $content string to send as response body
543544
* @return void
544545
*/
545546
protected function _sendContent($content)
546547
{
547-
echo $content;
548+
if (!is_string($content) && is_callable($content)) {
549+
call_user_func($content);
550+
} else {
551+
echo $content;
552+
}
548553
}
549554

550555
/**
@@ -629,7 +634,7 @@ public function location($url = null)
629634
* Buffers the response message to be sent
630635
* if $content is null the current buffer is returned
631636
*
632-
* @param string|null $content the string message to be sent
637+
* @param string|callable|null $content the string or callable message to be sent
633638
* @return string Current message buffer if $content param is passed as null
634639
*/
635640
public function body($content = null)
@@ -1228,11 +1233,15 @@ public function checkNotModified(Request $request)
12281233
/**
12291234
* String conversion. Fetches the response body as a string.
12301235
* Does *not* send headers.
1236+
* If body is a callable, a blank string is returned.
12311237
*
12321238
* @return string
12331239
*/
12341240
public function __toString()
12351241
{
1242+
if (!is_string($this->_body) && is_callable($this->_body)) {
1243+
return '';
1244+
}
12361245
return (string)$this->_body;
12371246
}
12381247

tests/TestCase/Network/ResponseTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,23 @@ public function testSendWithLocation()
314314
$response->send();
315315
}
316316

317+
/**
318+
* Tests the send method and changing the content type
319+
*
320+
* @return void
321+
*/
322+
public function testSendWithCallableBody()
323+
{
324+
$response = $this->getMock('Cake\Network\Response', ['_sendHeader']);
325+
$response->body(function () {
326+
echo 'the response body';
327+
});
328+
329+
ob_start();
330+
$response->send();
331+
$this->assertEquals('the response body', ob_get_clean());
332+
}
333+
317334
/**
318335
* Tests the disableCache method
319336
*

0 commit comments

Comments
 (0)