You are here

public function ReadOnlyModeMethodFilter::filter in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/Routing/ReadOnlyModeMethodFilter.php \Drupal\jsonapi\Routing\ReadOnlyModeMethodFilter::filter()

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

Parameters

\Symfony\Component\Routing\RouteCollection $collection: The collection against which to match.

\Symfony\Component\HttpFoundation\Request $request: A Request object against which to match.

Return value

\Symfony\Component\Routing\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 FilterInterface::filter

File

core/modules/jsonapi/src/Routing/ReadOnlyModeMethodFilter.php, line 47

Class

ReadOnlyModeMethodFilter
Filters routes based on the HTTP method and JSON:API's read-only mode.

Namespace

Drupal\jsonapi\Routing

Code

public function filter(RouteCollection $collection, Request $request) {
  $all_supported_methods = [];
  foreach ($collection
    ->all() as $name => $route) {
    $all_supported_methods = array_merge($all_supported_methods, $route
      ->getMethods());
  }
  $collection = $this->inner
    ->filter($collection, $request);
  if (!$this->readOnlyModeIsEnabled) {
    return $collection;
  }
  $read_only_methods = [
    'GET',
    'HEAD',
    'OPTIONS',
    'TRACE',
  ];
  foreach ($collection
    ->all() as $name => $route) {
    if (!$route
      ->hasDefault(Routes::JSON_API_ROUTE_FLAG_KEY)) {
      continue;
    }
    $supported_methods = $route
      ->getMethods();
    assert(count($supported_methods) > 0, 'JSON:API routes always have a method specified.');
    $is_read_only_route = empty(array_diff($supported_methods, $read_only_methods));
    if (!$is_read_only_route) {
      $collection
        ->remove($name);
    }
  }
  if (count($collection)) {
    return $collection;
  }
  throw new MethodNotAllowedHttpException(array_intersect($all_supported_methods, $read_only_methods), sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromRoute('jsonapi.settings')
    ->setAbsolute()
    ->toString(TRUE)
    ->getGeneratedUrl()));
}