Skip to content
Permalink
Browse files

Add the ability to set a callable response body.

  • Loading branch information...
reinink authored and ADmad committed Jun 29, 2015
1 parent f0d3a7a commit c37930b0b0b3da802a48b2f2435320d2a2ad5b37
Showing with 29 additions and 3 deletions.
  1. +12 −3 src/Network/Response.php
  2. +17 −0 tests/TestCase/Network/ResponseTest.php
@@ -335,7 +335,7 @@ class Response
protected $_headers = [];
/**
* Buffer string for response message
* Buffer string or callable for response message
*
* @var string
*/
@@ -538,13 +538,18 @@ protected function _sendHeader($name, $value = null)
/**
* Sends a content string to the client.
* If the content is a callable, it is invoked.
*
* @param string $content string to send as response body
* @return void
*/
protected function _sendContent($content)
{
echo $content;
if (!is_string($content) && is_callable($content)) {
call_user_func($content);
} else {
echo $content;
}
}
/**
@@ -629,7 +634,7 @@ public function location($url = null)
* Buffers the response message to be sent
* if $content is null the current buffer is returned
*
* @param string|null $content the string message to be sent
* @param string|callable|null $content the string or callable message to be sent
* @return string Current message buffer if $content param is passed as null
*/
public function body($content = null)
@@ -1228,11 +1233,15 @@ public function checkNotModified(Request $request)
/**
* String conversion. Fetches the response body as a string.
* Does *not* send headers.
* If body is a callable, a blank string is returned.
*
* @return string
*/
public function __toString()
{
if (!is_string($this->_body) && is_callable($this->_body)) {
return '';
}
return (string)$this->_body;
}
@@ -314,6 +314,23 @@ public function testSendWithLocation()
$response->send();
}
/**
* Tests the send method and changing the content type
*
* @return void
*/
public function testSendWithCallableBody()
{
$response = $this->getMock('Cake\Network\Response', ['_sendHeader']);
$response->body(function () {
echo 'the response body';
});
ob_start();
$response->send();
$this->assertEquals('the response body', ob_get_clean());
}
/**
* Tests the disableCache method
*

0 comments on commit c37930b

Please sign in to comment.
You can’t perform that action at this time.