Browse Source

Don't emit response bodies for 204 and 304 responses.

This makes the behavior of the PSR7 stack consistent with how CakePHP
has historically behaved.
Mark Story 9 years ago
parent
commit
5ec7c0e1e4
2 changed files with 27 additions and 0 deletions
  1. 3 0
      src/Http/ResponseEmitter.php
  2. 24 0
      tests/TestCase/Http/ResponseEmitterTest.php

+ 3 - 0
src/Http/ResponseEmitter.php

@@ -76,6 +76,9 @@ class ResponseEmitter implements EmitterInterface
      */
     protected function emitBody(ResponseInterface $response, $maxBufferLength)
     {
+        if (in_array($response->getStatusCode(), [204, 304])) {
+            return;
+        }
         $body = $response->getBody();
 
         if (!$body->isSeekable()) {

+ 24 - 0
tests/TestCase/Http/ResponseEmitterTest.php

@@ -64,6 +64,30 @@ class ResponseEmitterTest extends TestCase
     }
 
     /**
+     * Test emitting a no-content response
+     *
+     * @return void
+     */
+    public function testEmitNoContentResponse()
+    {
+        $response = (new Response())
+            ->withHeader('X-testing', 'value')
+            ->withStatus(204);
+        $response->getBody()->write('It worked');
+
+        ob_start();
+        $this->emitter->emit($response);
+        $out = ob_get_clean();
+
+        $this->assertEquals('', $out);
+        $expected = [
+            'HTTP/1.1 204 No Content',
+            'X-testing: value',
+        ];
+        $this->assertEquals($expected, $GLOBALS['mockedHeaders']);
+    }
+
+    /**
      * Test emitting responses with cookies
      *
      * @return void