You are here

public function ResourceRoutes::decorateJsonapiResourceRoutes in JSON:API Resources 8

Decorates JSON:API Resource routes.

Parameters

\Drupal\Core\Routing\RouteBuildEvent $event: The route rebuild event.

File

src/Unstable/Routing/ResourceRoutes.php, line 84

Class

ResourceRoutes
Route subscriber to decorate JSON:API Resource routes.

Namespace

Drupal\jsonapi_resources\Unstable\Routing

Code

public function decorateJsonapiResourceRoutes(RouteBuildEvent $event) {
  $route_collection = $event
    ->getRouteCollection();
  foreach ($route_collection as $route_name => $route) {
    if ($route
      ->getDefault('_jsonapi_resource') === NULL) {
      continue;
    }

    // Ensure that the declared implementation is valid.
    $this
      ->ensureResourceImplementationValid($route_name, $route);

    // Replace the %jsonapi% placeholder with the JSON:API base path.
    $path_segments = array_slice(explode('/', $route
      ->getPath()), 1);
    assert(isset($path_segments[0]) && $path_segments[0] === '%jsonapi%');
    $path_segments[0] = $this->jsonApiBasePath;
    $route
      ->setPath(implode('/', $path_segments));
    $route
      ->addRequirements([
      // Require the JSON:API media type header on every route.
      '_content_type_format' => 'api_json',
      // All routes serve only the JSON:API media type.
      '_format' => 'api_json',
    ]);

    // Enable all available authentication providers.
    $route
      ->addOptions([
      '_auth' => $this->providerIds,
    ]);

    // Flag every route as belonging to the JSON:API module.
    $route
      ->addDefaults([
      JsonapiRoutes::JSON_API_ROUTE_FLAG_KEY => TRUE,
    ]);
    $methods = $route
      ->getMethods();
    if (empty($methods)) {
      $route
        ->setMethods([
        'GET',
      ]);
    }
  }
}