bug #20289 Fix edge case with StreamedResponse where headers are sent twice (Nicofuma)

This PR was merged into the 2.7 branch.

Discussion
----------

Fix edge case with StreamedResponse where headers are sent twice

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes/no
| Fixed tickets |
| License       | MIT
| Doc PR        |

If you have PHPs output buffering enabled (`output_buffering=4096` in your php.ini per example), there is an edge case with the StreamedResponse object where the headers are sent twice. Even if it is harmless most of the time, it can be critical sometimes (per example, if an `Access-Control-Allow-Origin` header is duplicated the browser will block the request).

Explanation: because the streamed response may need the request in order to generate the content, the `StreamedResponseListener` class calls the send method of the `Response` when the event `kernel.response` is fired. To prevent the content from being duplicated, a state has been introduced in the `sendContent()` method and it works fine.

But there is an edge case is the headers of the response. If the content generated by the `sendContent()` method is smaller than the value defined for `output_buffering` in the `php.ini` then the buffer won't be flushed and the `headers_sent()` function will return false.
Therefore when `$response->send()` is called for the second time (in the `app.php` file), the headers will be sent a second time.

Commits
-------

a79991f Fix edge case with StreamedResponse where headers are sent twice
This commit is contained in:
Fabien Potencier 2016-10-24 08:51:37 -07:00
commit 6bca8afb31

View File

@ -28,6 +28,7 @@ class StreamedResponse extends Response
{
protected $callback;
protected $streamed;
private $headersSent;
/**
* Constructor.
@ -44,6 +45,7 @@ class StreamedResponse extends Response
$this->setCallback($callback);
}
$this->streamed = false;
$this->headersSent = false;
}
/**
@ -75,6 +77,22 @@ class StreamedResponse extends Response
$this->callback = $callback;
}
/**
* {@inheritdoc}
*
* This method only sends the headers once.
*/
public function sendHeaders()
{
if ($this->headersSent) {
return;
}
$this->headersSent = true;
parent::sendHeaders();
}
/**
* {@inheritdoc}
*