Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding length() method to CakeResponse as a shortcut for Content-Leng…

…th. If you wish to force not Content-Length use length(false)
  • Loading branch information...
commit 5b42cb8130bd22eef6d0eb0c48ce2c6130dc853e 1 parent 336ba19
@lorenzo lorenzo authored
View
26 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));
}
}
}
@@ -697,6 +701,22 @@ public function protocol($protocol = null) {
}
/**
+ * 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.
*
View
21 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();
+ }
}
Please sign in to comment.
Something went wrong with that request. Please try again.