[HttpFoundation] Accept must take the lead for Request::getPreferredFormat()
This commit is contained in:
parent
b79a1bf229
commit
60d997df75
@ -1347,6 +1347,8 @@ class Request
|
||||
* * _format request attribute
|
||||
* * $default
|
||||
*
|
||||
* @see getPreferredFormat
|
||||
*
|
||||
* @param string|null $default The default format
|
||||
*
|
||||
* @return string|null The request format
|
||||
@ -1563,21 +1565,26 @@ class Request
|
||||
return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the preferred format for the response by inspecting, in the following order:
|
||||
* * the request format set using setRequestFormat
|
||||
* * the values of the Accept HTTP header
|
||||
* * the content type of the body of the request.
|
||||
*/
|
||||
public function getPreferredFormat(?string $default = 'html'): ?string
|
||||
{
|
||||
if (null !== $this->preferredFormat) {
|
||||
return $this->preferredFormat;
|
||||
}
|
||||
|
||||
$this->preferredFormat = $this->getRequestFormat($this->getContentType());
|
||||
|
||||
if (null === $this->preferredFormat) {
|
||||
$preferredFormat = null;
|
||||
foreach ($this->getAcceptableContentTypes() as $contentType) {
|
||||
if (null !== $this->preferredFormat = $this->getFormat($contentType)) {
|
||||
if ($preferredFormat = $this->getFormat($contentType)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->preferredFormat = $this->getRequestFormat($preferredFormat ?: $this->getContentType());
|
||||
|
||||
return $this->preferredFormat ?: $default;
|
||||
}
|
||||
|
@ -407,14 +407,14 @@ class RequestTest extends TestCase
|
||||
$this->assertSame('json', $request->getPreferredFormat('json'));
|
||||
|
||||
$request->setRequestFormat('atom');
|
||||
$request->headers->set('Content-Type', 'application/json');
|
||||
$request->headers->set('Accept', 'application/xml');
|
||||
$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('Content-Type', 'application/json');
|
||||
$request->headers->set('Accept', 'application/xml');
|
||||
$this->assertSame('json', $request->getPreferredFormat());
|
||||
$request->headers->set('Content-Type', 'application/json');
|
||||
$this->assertSame('xml', $request->getPreferredFormat());
|
||||
|
||||
$request = new Request();
|
||||
$request->headers->set('Accept', 'application/xml');
|
||||
|
@ -504,6 +504,7 @@ class ResponseTest extends ResponseTestCase
|
||||
$response = new Response('foo');
|
||||
$request = Request::create('/');
|
||||
$request->setRequestFormat('json');
|
||||
$request->headers->remove('accept');
|
||||
|
||||
$response->prepare($request);
|
||||
|
||||
|
Reference in New Issue
Block a user