Skip to content
This repository
Browse code

Saving a few bytes by unsetting the content if the response status co…

…de is 204 (No Content) or 304 (Not Modified)
  • Loading branch information...
commit 4d19d536f6998a2d1dc32564751be674298702f5 1 parent 5b42cb8
José Lorenzo Rodríguez authored November 04, 2011
12  lib/Cake/Network/CakeResponse.php
@@ -349,6 +349,7 @@ public function send() {
349 349
 		$codeMessage = $this->_statusCodes[$this->_status];
350 350
 		$this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
351 351
 		$this->_sendHeader('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
  352
+		$this->_setContent();
352 353
 		$this->_setContentLength();
353 354
 		foreach ($this->_headers as $header => $value) {
354 355
 			$this->_sendHeader($header, $value);
@@ -357,6 +358,17 @@ public function send() {
357 358
 	}
358 359
 
359 360
 /**
  361
+ * Sets the response body to an empty text if the status code is 204 or 304
  362
+ *
  363
+ * @return void
  364
+ */
  365
+	protected function _setContent() {
  366
+		if (in_array($this->_status, array(304, 204))) {
  367
+			$this->body('');
  368
+		}
  369
+	}
  370
+
  371
+/**
360 372
  * Calculates the correct Content-Length and sets it as a header in the response
361 373
  * Will not set the value if already set or if the output is compressed.
362 374
  *
28  lib/Cake/Test/Case/Network/CakeResponseTest.php
@@ -535,4 +535,32 @@ public function testLength() {
535 535
 			->method('_sendHeader');
536 536
 		$response->send();
537 537
 	}
  538
+
  539
+/**
  540
+ * Tests that the response body is unset if the status code is 304 or 204
  541
+ *
  542
+ * @return void
  543
+ */
  544
+	public function testUnmodifiedContent() {
  545
+		$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
  546
+		$response->body('This is a body');
  547
+		$response->statusCode(204);
  548
+		$response->expects($this->once())
  549
+			->method('_sendContent')->with('');
  550
+		$response->send();
  551
+
  552
+		$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
  553
+		$response->body('This is a body');
  554
+		$response->statusCode(304);
  555
+		$response->expects($this->once())
  556
+			->method('_sendContent')->with('');
  557
+		$response->send();
  558
+
  559
+		$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
  560
+		$response->body('This is a body');
  561
+		$response->statusCode(200);
  562
+		$response->expects($this->once())
  563
+			->method('_sendContent')->with('This is a body');
  564
+		$response->send();
  565
+	}
538 566
 }

0 notes on commit 4d19d53

Please sign in to comment.
Something went wrong with that request. Please try again.