a90d4f4607c8ad527f86e95834aa4303b7b3f38a
[yaffs-website] / web / core / modules / system / tests / modules / accept_header_routing_test / src / Routing / AcceptHeaderMatcher.php
1 <?php
2
3 namespace Drupal\accept_header_routing_test\Routing;
4
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;
9
10 /**
11  * Filters routes based on the media type specified in the HTTP Accept headers.
12  */
13 class AcceptHeaderMatcher implements FilterInterface {
14
15   /**
16    * {@inheritdoc}
17    */
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();
24
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')));
28
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);
33       }
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.
37       }
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);
44       }
45       else {
46         // Remove the route if it does not match at all.
47         $collection->remove($name);
48       }
49     }
50
51     if (count($collection)) {
52       return $collection;
53     }
54
55     // We do not throw a
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));
59   }
60
61 }