Skip to content
Permalink
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...
lorenzo committed Nov 4, 2011
1 parent 336ba19 commit 5b42cb8130bd22eef6d0eb0c48ce2c6130dc853e
Showing with 44 additions and 3 deletions.
  1. +23 −3 lib/Cake/Network/CakeResponse.php
  2. +21 −0 lib/Cake/Test/Case/Network/CakeResponseTest.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.
@@ -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();
}
}

0 comments on commit 5b42cb8

Please sign in to comment.
You can’t perform that action at this time.