3 namespace Drupal\Core\Routing;
5 use Symfony\Component\HttpFoundation\Request;
6 use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
7 use Symfony\Component\Routing\RouteCollection;
10 * Filters routes based on the HTTP Content-type header.
12 class ContentTypeHeaderMatcher implements FilterInterface {
17 public function filter(RouteCollection $collection, Request $request) {
18 // The Content-type header does not make sense on GET or DELETE requests,
19 // because they do not carry any content. Nothing to filter in this case.
20 // Same for all other safe methods.
21 if ($request->isMethodSafe(FALSE) || $request->isMethod('DELETE')) {
25 $format = $request->getContentType();
27 foreach ($collection as $name => $route) {
28 $supported_formats = array_filter(explode('|', $route->getRequirement('_content_type_format')));
29 if (empty($supported_formats)) {
30 // No restriction on the route, so we move the route to the end of the
31 // collection by re-adding it. That way generic routes sink down in the
32 // list and exact matching routes stay on top.
33 $collection->add($name, $route);
35 elseif (!in_array($format, $supported_formats)) {
36 $collection->remove($name);
39 if (count($collection)) {
43 // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
44 // because we don't want to return a 404 status code, but rather a 415.
45 if (!$request->headers->has('Content-Type')) {
46 throw new UnsupportedMediaTypeHttpException('No "Content-Type" request header specified');
49 throw new UnsupportedMediaTypeHttpException('No route found that matches "Content-Type: ' . $request->headers->get('Content-Type') . '"');