diff --git a/lib/Cake/Network/CakeResponse.php b/lib/Cake/Network/CakeResponse.php index 74113c63a42..549b71aa3d4 100644 --- a/lib/Cake/Network/CakeResponse.php +++ b/lib/Cake/Network/CakeResponse.php @@ -363,13 +363,17 @@ public function send() { * @return void */ protected function _setContentLength() { - $shouldSetLength = empty($this->_headers['Content-Length']) && !in_array($this->_status, range(301, 307)); + $shouldSetLength = !isset($this->_headers['Content-Length']) && !in_array($this->_status, range(301, 307)); + if (isset($this->_headers['Content-Length']) && $this->_headers['Content-Length'] === false) { + unset($this->_headers['Content-Length']); + return; + } if ($shouldSetLength && !$this->outputCompressed()) { $offset = ob_get_level() ? ob_get_length() : 0; if (ini_get('mbstring.func_overload') & 2 && function_exists('mb_strlen')) { - $this->_headers['Content-Length'] = $offset + mb_strlen($this->_body, '8bit'); + $this->length($offset + mb_strlen($this->_body, '8bit')); } else { - $this->_headers['Content-Length'] = $offset + strlen($this->_body); + $this->length($this->_headers['Content-Length'] = $offset + strlen($this->_body)); } } } @@ -696,6 +700,22 @@ public function protocol($protocol = null) { return $this->_protocol; } +/** + * Sets the Content-Length header for the response + * If called with no arguments returns the last Content-Length set + * + * @return int + */ + public function length($bytes = null) { + if ($bytes !== null ) { + $this->_headers['Content-Length'] = $bytes; + } + if (isset($this->_headers['Content-Length'])) { + return $this->_headers['Content-Length']; + } + return null; + } + /** * String conversion. Fetches the response body as a string. * Does *not* send headers. diff --git a/lib/Cake/Test/Case/Network/CakeResponseTest.php b/lib/Cake/Test/Case/Network/CakeResponseTest.php index fc38218cfff..cb66280f627 100644 --- a/lib/Cake/Test/Case/Network/CakeResponseTest.php +++ b/lib/Cake/Test/Case/Network/CakeResponseTest.php @@ -514,4 +514,25 @@ public function testProtocol() { ->method('_sendHeader')->with('HTTP/1.0 200 OK'); $response->send(); } + +/** + * Tests getting/setting the Content-Length + * + * @return void + */ + public function testLength() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->length(100); + $this->assertEquals(100, $response->length()); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Length', 100); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->length(false); + $this->assertFalse($response->length()); + $response->expects($this->exactly(2)) + ->method('_sendHeader'); + $response->send(); + } }