diff --git a/src/Symfony/Component/HttpFoundation/CHANGELOG.md b/src/Symfony/Component/HttpFoundation/CHANGELOG.md index fdbd39cead31..29bc7507e58b 100644 --- a/src/Symfony/Component/HttpFoundation/CHANGELOG.md +++ b/src/Symfony/Component/HttpFoundation/CHANGELOG.md @@ -6,6 +6,7 @@ CHANGELOG * Add stale while revalidate and stale if error cache header * Allow dynamic session "ttl" when using a remote storage + * Send `Content-Length` when calling `Response::send()` and the content is a non-empty string 6.0 --- diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php index e452e1a017f3..da5cec540522 100644 --- a/src/Symfony/Component/HttpFoundation/Response.php +++ b/src/Symfony/Component/HttpFoundation/Response.php @@ -371,6 +371,10 @@ public function sendContent(): static */ public function send(): static { + if (\is_string($this->content) && '' !== $this->content && !$this->headers->has('Transfer-Encoding')) { + $this->headers->set('Content-Length', \strlen($this->content)); + } + $this->sendHeaders(); $this->sendContent(); diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php index af4b29e042f7..9d4a32a54269 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php @@ -50,13 +50,27 @@ public function testSendHeaders() public function testSend() { $response = new Response(); - $responseSend = $response->send(); - $this->assertObjectHasAttribute('headers', $responseSend); - $this->assertObjectHasAttribute('content', $responseSend); - $this->assertObjectHasAttribute('version', $responseSend); - $this->assertObjectHasAttribute('statusCode', $responseSend); - $this->assertObjectHasAttribute('statusText', $responseSend); - $this->assertObjectHasAttribute('charset', $responseSend); + $responseSent = $response->send(); + $this->assertObjectHasAttribute('headers', $responseSent); + $this->assertObjectHasAttribute('content', $responseSent); + $this->assertObjectHasAttribute('version', $responseSent); + $this->assertObjectHasAttribute('statusCode', $responseSent); + $this->assertObjectHasAttribute('statusText', $responseSent); + $this->assertObjectHasAttribute('charset', $responseSent); + $this->assertFalse($responseSent->headers->has('Content-Length')); + + ob_start(); + + $response = new Response('foo'); + $responseSent = $response->send(); + $this->assertSame('3', $responseSent->headers->get('Content-Length')); + + $response = new Response('bar'); + $response->headers->set('Transfer-Encoding', 'chunked'); + $responseSent = $response->send(); + $this->assertFalse($responseSent->headers->has('Content-Length')); + + $this->assertSame('foobar', ob_get_clean()); } public function testGetCharset()