bug #34921 [HttpFoundation] Removed "Content-Type" from the preferred format guessing mechanism (yceruto)

This PR was merged into the 4.4 branch.

Discussion
----------

[HttpFoundation] Removed "Content-Type" from the preferred format guessing mechanism

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #34906, Fix #34857
| License       | MIT
| Doc PR        | -

Confirmed, inferring the `Content-Type` of the response using the `Content-Type` provided for the request body is NOT a good idea. The HTTP RFC explicitly states that `Accept` must be used to hint a preferred response format (`Content-Type` on the request indicates the type of associated its the body).

Use `Accept` if provided (a best practice anyway), and fallback to the default value (HTML by default) otherwise.

Commits
-------

776523e56a Removed request header "Content-Type" from the preferred format guessing mechanism
This commit is contained in:
Fabien Potencier 2019-12-11 01:19:19 +01:00
commit d91efd31f6
2 changed files with 5 additions and 10 deletions

View File

@ -1586,20 +1586,17 @@ class Request
*/
public function getPreferredFormat(?string $default = 'html'): ?string
{
if (null !== $this->preferredFormat) {
if (null !== $this->preferredFormat || null !== $this->preferredFormat = $this->getRequestFormat(null)) {
return $this->preferredFormat;
}
$preferredFormat = null;
foreach ($this->getAcceptableContentTypes() as $contentType) {
if ($preferredFormat = $this->getFormat($contentType)) {
break;
foreach ($this->getAcceptableContentTypes() as $mimeType) {
if ($this->preferredFormat = $this->getFormat($mimeType)) {
return $this->preferredFormat;
}
}
$this->preferredFormat = $this->getRequestFormat($preferredFormat ?: $this->getContentType());
return $this->preferredFormat ?: $default;
return $default;
}
/**

View File

@ -408,12 +408,10 @@ class RequestTest extends TestCase
$request->setRequestFormat('atom');
$request->headers->set('Accept', 'application/ld+json');
$request->headers->set('Content-Type', 'application/merge-patch+json');
$this->assertSame('atom', $request->getPreferredFormat());
$request = new Request();
$request->headers->set('Accept', 'application/xml');
$request->headers->set('Content-Type', 'application/json');
$this->assertSame('xml', $request->getPreferredFormat());
$request = new Request();