From 4fc472d9a7595fbd45ee56d3f5ed50704fac2762 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 18 Oct 2016 21:31:23 -0400 Subject: [PATCH] Don't eagerly call callback responses. Don't eagerly evaluate callback/streaming responses. This can result in allocating a pile of memory too soon in the request. Instead it is preferrable to allocate that memory when we're flushing to the SAPI. --- src/Network/Response.php | 25 +++++++++++-------------- tests/TestCase/Network/ResponseTest.php | 1 - 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/Network/Response.php b/src/Network/Response.php index 22f6908823e..f80ad7b197a 100644 --- a/src/Network/Response.php +++ b/src/Network/Response.php @@ -16,6 +16,7 @@ use Cake\Core\Configure; use Cake\Filesystem\File; +use Cake\Http\CallbackStream; use Cake\Log\Log; use Cake\Network\Exception\NotFoundException; use DateTime; @@ -739,30 +740,26 @@ protected function _setHeader($header, $value) public function body($content = null) { if ($content === null) { - $this->stream->rewind(); + if ($this->stream->isSeekable()) { + $this->stream->rewind(); + } $result = $this->stream->getContents(); - if (empty($result) && strlen($result) === 0) { + if (strlen($result) === 0) { return null; } return $result; } - // BC compatibility + // Compatibility with closure/streaming responses if (is_callable($content)) { - $content = $this->_handleCallableBody($content); - } - - $this->_createStream(); - $this->stream->write($content); - $this->stream->rewind(); - $result = $this->stream->getContents(); - - if (empty($result) && strlen($result) === 0) { - return null; + $this->stream = new CallbackStream($content); + } else { + $this->_createStream(); + $this->stream->write($content); } - return $result; + return $content; } /** diff --git a/tests/TestCase/Network/ResponseTest.php b/tests/TestCase/Network/ResponseTest.php index 75dfc8ec283..c566b6d1e84 100644 --- a/tests/TestCase/Network/ResponseTest.php +++ b/tests/TestCase/Network/ResponseTest.php @@ -2350,5 +2350,4 @@ public function testHasHeader() $this->assertFalse($response->hasHeader('Accept')); $this->assertFalse($response->hasHeader('accept')); } - }