Skip to content

[HttpFoundation] Default request _format should be aware of HTTP Accept header #6276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Symfony/Component/HttpFoundation/AcceptHeader.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ public function __construct(array $items)
*/
public static function fromString($headerValue)
{
if (empty($headerValue)) {
return new self(array());
}

$index = 0;

return new self(array_map(function ($itemValue) use (&$index) {
Expand Down
8 changes: 7 additions & 1 deletion src/Symfony/Component/HttpFoundation/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,7 @@ public function setFormat($format, $mimeTypes)
*
* * format defined by the user (with setRequestFormat())
* * _format request parameter
* * `Accept` header value
* * $default
*
* @param string $default The default format
Expand All @@ -1158,7 +1159,12 @@ public function setFormat($format, $mimeTypes)
public function getRequestFormat($default = 'html')
{
if (null === $this->format) {
$this->format = $this->get('_format', $default);
$format = AcceptHeader::fromString($this->headers->get('Accept'))->first();
if ($format) {
$format = $this->getFormat($format->getValue());
}

$this->format = $this->get('_format', $format ?: $default);
}

return $this->format;
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/HttpFoundation/Tests/RequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,16 @@ public function testGetRequestFormat()
$request = new Request();
$this->assertNull($request->setRequestFormat('foo'));
$this->assertEquals('foo', $request->getRequestFormat(null));

$request = new Request();
$request->headers->set('Accept', 'text/xml,application/xml;q=0.9,*/*;q=0.8');
$this->assertEquals('xml', $request->getRequestFormat());
$this->assertEquals('xml', $request->getRequestFormat('json'));

$request = new Request();
$request->headers->set('Accept', 'text/xml,application/xml;q=0.9,*/*;q=0.8');
$request->setRequestFormat('foo');
$this->assertEquals('foo', $request->getRequestFormat());
}

public function testHasSession()
Expand Down