Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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 Jan 19, 2012
1 parent 336ba19 commit 5b42cb8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
26 changes: 23 additions & 3 deletions lib/Cake/Network/CakeResponse.php
Expand Up @@ -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));
}
}
}
Expand Down Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions lib/Cake/Test/Case/Network/CakeResponseTest.php
Expand Up @@ -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.