Browse Source

Add the ability to set a callable response body.

Jonathan Reinink 10 years ago
parent
commit
c37930b0b0
2 changed files with 29 additions and 3 deletions
  1. 12 3
      src/Network/Response.php
  2. 17 0
      tests/TestCase/Network/ResponseTest.php

+ 12 - 3
src/Network/Response.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 @@ class Response
 
     /**
      * 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 @@ class Response
      * 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 @@ class Response
     /**
      * 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;
     }
 

+ 17 - 0
tests/TestCase/Network/ResponseTest.php

@@ -315,6 +315,23 @@ class ResponseTest extends TestCase
     }
 
     /**
+     * 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
      *
      * @return void