Skip to content

Commit

Permalink
Add the ability to set a callable response body.
Browse files Browse the repository at this point in the history
  • Loading branch information
reinink authored and ADmad committed Jul 7, 2015
1 parent f0d3a7a commit c37930b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/Network/Response.php
Expand Up @@ -335,7 +335,7 @@ class Response
protected $_headers = [];

/**
* Buffer string for response message
* Buffer string or callable for response message
*
* @var string
*/
Expand Down Expand Up @@ -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;
}
}

/**
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
}

Expand Down
17 changes: 17 additions & 0 deletions tests/TestCase/Network/ResponseTest.php
Expand Up @@ -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
*
Expand Down

0 comments on commit c37930b

Please sign in to comment.