You are here

protected function ResourceRoutes::alterRoutes in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/modules/rest/src/Routing/ResourceRoutes.php \Drupal\rest\Routing\ResourceRoutes::alterRoutes()

Alters existing routes for a specific collection.

Parameters

\Symfony\Component\Routing\RouteCollection $collection: The route collection for adding routes.

Return value

array

Overrides RouteSubscriberBase::alterRoutes

File

core/modules/rest/src/Routing/ResourceRoutes.php, line 65
Contains \Drupal\rest\Routing\ResourceRoutes.

Class

ResourceRoutes
Subscriber for REST-style routes.

Namespace

Drupal\rest\Routing

Code

protected function alterRoutes(RouteCollection $collection) {
  $routes = array();
  $enabled_resources = $this->config
    ->get('rest.settings')
    ->get('resources') ?: array();

  // Iterate over all enabled resource plugins.
  foreach ($enabled_resources as $id => $enabled_methods) {
    $plugin = $this->manager
      ->getInstance(array(
      'id' => $id,
    ));
    foreach ($plugin
      ->routes() as $name => $route) {

      // @todo: Are multiple methods possible here?
      $methods = $route
        ->getMethods();

      // Only expose routes where the method is enabled in the configuration.
      if ($methods && ($method = $methods[0]) && $method && isset($enabled_methods[$method])) {
        $route
          ->setRequirement('_access_rest_csrf', 'TRUE');

        // Check that authentication providers are defined.
        if (empty($enabled_methods[$method]['supported_auth']) || !is_array($enabled_methods[$method]['supported_auth'])) {
          $this->logger
            ->error('At least one authentication provider must be defined for resource @id', array(
            ':id' => $id,
          ));
          continue;
        }

        // Check that formats are defined.
        if (empty($enabled_methods[$method]['supported_formats']) || !is_array($enabled_methods[$method]['supported_formats'])) {
          $this->logger
            ->error('At least one format must be defined for resource @id', array(
            ':id' => $id,
          ));
          continue;
        }

        // If the route has a format requirement, then verify that the
        // resource has it.
        $format_requirement = $route
          ->getRequirement('_format');
        if ($format_requirement && !in_array($format_requirement, $enabled_methods[$method]['supported_formats'])) {
          continue;
        }

        // The configuration seems legit at this point, so we set the
        // authentication provider and add the route.
        $route
          ->setOption('_auth', $enabled_methods[$method]['supported_auth']);
        $routes["rest.{$name}"] = $route;
        $collection
          ->add("rest.{$name}", $route);
      }
    }
  }
}