public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->attributes->has('_api_resource_class') && !$request->attributes->has('_api_respond')) {
return;
}
$this->populateMimeTypes();
$this->addRequestFormats($request, $this->formats);
// Empty strings must be converted to null because the Symfony router doesn't support parameter typing before 3.2 (_format)
if (null === ($routeFormat = $request->attributes->get('_format') ?: null)) {
$mimeTypes = array_keys($this->mimeTypes);
} elseif (!isset($this->formats[$routeFormat])) {
throw new NotFoundHttpException('Not Found');
} else {
$mimeTypes = Request::getMimeTypes($routeFormat);
}
// First, try to guess the format from the Accept header
$accept = $request->headers->get('Accept');
if (null !== $accept) {
if (null === ($acceptHeader = $this->negotiator->getBest($accept, $mimeTypes))) {
throw $this->getNotAcceptableHttpException($accept, $mimeTypes);
}
$request->setRequestFormat($request->getFormat($acceptHeader->getType()));
return;
}
// Then use the Symfony request format if available and applicable
$requestFormat = $request->getRequestFormat(null) ?: null;
if (null !== $requestFormat) {
$mimeType = $request->getMimeType($requestFormat);
if (isset($this->mimeTypes[$mimeType])) {
return;
}
throw $this->getNotAcceptableHttpException($mimeType);
}
// Finally, if no Accept header nor Symfony request format is set, return the default format
reset($this->formats);
$request->setRequestFormat(each($this->formats)['key']);
}