3 namespace Drupal\accept_header_routing_test\Routing;
5 use Drupal\Core\Routing\FilterInterface;
6 use Symfony\Component\HttpFoundation\Request;
7 use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
8 use Symfony\Component\Routing\RouteCollection;
11 * Filters routes based on the media type specified in the HTTP Accept headers.
13 class AcceptHeaderMatcher implements FilterInterface {
18 public function filter(RouteCollection $collection, Request $request) {
19 // Generates a list of Symfony formats matching the acceptable MIME types.
20 // @todo replace by proper content negotiation library.
21 $acceptable_mime_types = $request->getAcceptableContentTypes();
22 $acceptable_formats = array_filter(array_map([$request, 'getFormat'], $acceptable_mime_types));
23 $primary_format = $request->getRequestFormat();
25 foreach ($collection as $name => $route) {
26 // _format could be a |-delimited list of supported formats.
27 $supported_formats = array_filter(explode('|', $route->getRequirement('_format')));
29 if (empty($supported_formats)) {
30 // No format restriction on the route, so it always matches. Move it to
31 // the end of the collection by re-adding it.
32 $collection->add($name, $route);
34 elseif (in_array($primary_format, $supported_formats)) {
35 // Perfect match, which will get a higher priority by leaving the route
36 // on top of the list.
38 // The route partially matches if it doesn't care about format, if it
39 // explicitly allows any format, or if one of its allowed formats is
40 // in the request's list of acceptable formats.
41 elseif (in_array('*/*', $acceptable_mime_types) || array_intersect($acceptable_formats, $supported_formats)) {
42 // Move it to the end of the list.
43 $collection->add($name, $route);
46 // Remove the route if it does not match at all.
47 $collection->remove($name);
51 if (count($collection)) {
56 // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
57 // because we don't want to return a 404 status code, but rather a 406.
58 throw new NotAcceptableHttpException('No route found for the specified formats ' . implode(' ', $acceptable_mime_types));