Saving a few bytes by unsetting the content if the response status code is 204 (No Content) or 304 (Not Modified)

This commit is contained in:
Jose Lorenzo Rodriguez 2011-11-04 15:36:47 -04:30
parent 5b42cb8130
commit 4d19d536f6
2 changed files with 40 additions and 0 deletions

View file

@ -349,6 +349,7 @@ class CakeResponse {
$codeMessage = $this->_statusCodes[$this->_status]; $codeMessage = $this->_statusCodes[$this->_status];
$this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}"); $this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
$this->_sendHeader('Content-Type', "{$this->_contentType}; charset={$this->_charset}"); $this->_sendHeader('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
$this->_setContent();
$this->_setContentLength(); $this->_setContentLength();
foreach ($this->_headers as $header => $value) { foreach ($this->_headers as $header => $value) {
$this->_sendHeader($header, $value); $this->_sendHeader($header, $value);
@ -356,6 +357,17 @@ class CakeResponse {
$this->_sendContent($this->_body); $this->_sendContent($this->_body);
} }
/**
* Sets the response body to an empty text if the status code is 204 or 304
*
* @return void
*/
protected function _setContent() {
if (in_array($this->_status, array(304, 204))) {
$this->body('');
}
}
/** /**
* Calculates the correct Content-Length and sets it as a header in the response * Calculates the correct Content-Length and sets it as a header in the response
* Will not set the value if already set or if the output is compressed. * Will not set the value if already set or if the output is compressed.

View file

@ -535,4 +535,32 @@ class CakeResponseTest extends CakeTestCase {
->method('_sendHeader'); ->method('_sendHeader');
$response->send(); $response->send();
} }
/**
* Tests that the response body is unset if the status code is 304 or 204
*
* @return void
*/
public function testUnmodifiedContent() {
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->body('This is a body');
$response->statusCode(204);
$response->expects($this->once())
->method('_sendContent')->with('');
$response->send();
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->body('This is a body');
$response->statusCode(304);
$response->expects($this->once())
->method('_sendContent')->with('');
$response->send();
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->body('This is a body');
$response->statusCode(200);
$response->expects($this->once())
->method('_sendContent')->with('This is a body');
$response->send();
}
} }