You are here

public function ContentTypeHeaderMatcher::filter in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/Routing/ContentTypeHeaderMatcher.php \Drupal\Core\Routing\ContentTypeHeaderMatcher::filter()

Filters the route collection against a request and returns all matching routes.

Parameters

RouteCollection $collection The collection against which to match.:

Request $request A Request object against which to match.:

Return value

RouteCollection A non-empty RouteCollection of matched routes.

Throws

ResourceNotFoundException if none of the routes in $collection matches $request. This is a performance optimization to not continue the match process when a match will no longer be possible.

Overrides RouteFilterInterface::filter

File

core/lib/Drupal/Core/Routing/ContentTypeHeaderMatcher.php, line 23
Contains \Drupal\Core\Routing\ContentTypeHeaderMatcher.

Class

ContentTypeHeaderMatcher
Filters routes based on the HTTP Content-type header.

Namespace

Drupal\Core\Routing

Code

public function filter(RouteCollection $collection, Request $request) {

  // The Content-type header does not make sense on GET requests, because GET
  // requests do not carry any content. Nothing to filter in this case.
  if ($request
    ->isMethod('GET')) {
    return $collection;
  }
  $format = $request
    ->getContentType();
  foreach ($collection as $name => $route) {
    $supported_formats = array_filter(explode('|', $route
      ->getRequirement('_content_type_format')));
    if (empty($supported_formats)) {

      // No restriction on the route, so we move the route to the end of the
      // collection by re-adding it. That way generic routes sink down in the
      // list and exact matching routes stay on top.
      $collection
        ->add($name, $route);
    }
    elseif (!in_array($format, $supported_formats)) {
      $collection
        ->remove($name);
    }
  }
  if (count($collection)) {
    return $collection;
  }

  // We do not throw a
  // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
  // because we don't want to return a 404 status code, but rather a 415.
  throw new UnsupportedMediaTypeHttpException('No route found that matches the Content-Type header.');
}