Skip to content

Commit 38a3244

Browse files
[HttpFoundation] Send Content-Length when calling Response::send() and the content is a non-empty string
1 parent edd1dfb commit 38a3244

File tree

3 files changed

+26
-7
lines changed

3 files changed

+26
-7
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ CHANGELOG
66

77
* Add stale while revalidate and stale if error cache header
88
* Allow dynamic session "ttl" when using a remote storage
9+
* Send `Content-Length` when calling `Response::send()` and the content is a non-empty string
910

1011
6.0
1112
---

Response.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,10 @@ public function sendContent(): static
371371
*/
372372
public function send(): static
373373
{
374+
if (\is_string($this->content) && '' !== $this->content && !$this->headers->has('Transfer-Encoding')) {
375+
$this->headers->set('Content-Length', \strlen($this->content));
376+
}
377+
374378
$this->sendHeaders();
375379
$this->sendContent();
376380

Tests/ResponseTest.php

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,27 @@ public function testSendHeaders()
5050
public function testSend()
5151
{
5252
$response = new Response();
53-
$responseSend = $response->send();
54-
$this->assertObjectHasAttribute('headers', $responseSend);
55-
$this->assertObjectHasAttribute('content', $responseSend);
56-
$this->assertObjectHasAttribute('version', $responseSend);
57-
$this->assertObjectHasAttribute('statusCode', $responseSend);
58-
$this->assertObjectHasAttribute('statusText', $responseSend);
59-
$this->assertObjectHasAttribute('charset', $responseSend);
53+
$responseSent = $response->send();
54+
$this->assertObjectHasAttribute('headers', $responseSent);
55+
$this->assertObjectHasAttribute('content', $responseSent);
56+
$this->assertObjectHasAttribute('version', $responseSent);
57+
$this->assertObjectHasAttribute('statusCode', $responseSent);
58+
$this->assertObjectHasAttribute('statusText', $responseSent);
59+
$this->assertObjectHasAttribute('charset', $responseSent);
60+
$this->assertFalse($responseSent->headers->has('Content-Length'));
61+
62+
ob_start();
63+
64+
$response = new Response('foo');
65+
$responseSent = $response->send();
66+
$this->assertSame('3', $responseSent->headers->get('Content-Length'));
67+
68+
$response = new Response('bar');
69+
$response->headers->set('Transfer-Encoding', 'chunked');
70+
$responseSent = $response->send();
71+
$this->assertFalse($responseSent->headers->has('Content-Length'));
72+
73+
$this->assertSame('foobar', ob_get_clean());
6074
}
6175

6276
public function testGetCharset()

0 commit comments

Comments
 (0)