You are here

public function Routes::routes in JSON:API Search API 8

1 string reference to 'Routes::routes'
jsonapi_search_api.routing.yml in ./jsonapi_search_api.routing.yml
jsonapi_search_api.routing.yml

File

src/Routing/Routes.php, line 80

Class

Routes

Namespace

Drupal\jsonapi_search_api\Routing

Code

public function routes() : RouteCollection {
  $routes = new RouteCollection();
  $index_storage = $this->entityTypeManager
    ->getStorage('search_api_index');
  $indexes = $index_storage
    ->loadMultiple();
  foreach ($indexes as $index) {
    assert($index instanceof IndexInterface);
    if (!$index
      ->status()) {
      continue;
    }
    $resource_types = [];
    foreach ($index
      ->getDatasources() as $datasource) {
      assert($datasource instanceof DatasourceInterface);
      $entity_type_id = $datasource
        ->getEntityTypeId();
      if ($this->entityTypeManager
        ->hasDefinition($entity_type_id)) {
        foreach (array_keys($datasource
          ->getBundles()) as $bundle) {
          $resource_type = $this->resourceTypeRepository
            ->get($entity_type_id, $bundle);
          if ($resource_type) {
            $resource_types[] = $resource_type
              ->getTypeName();
          }
        }
      }
    }
    $route = new Route('/index/' . $index
      ->id());
    $route
      ->addDefaults([
      '_jsonapi_resource' => IndexResource::class,
      '_jsonapi_resource_types' => $resource_types,
      'index' => $index
        ->uuid(),
    ]);
    $parameters = $route
      ->getOption('parameters') ?: [];
    $parameters['index']['type'] = 'entity:search_api_index';
    $route
      ->setOption('parameters', $parameters);
    $root_resource_type = $this->resourceTypeRepository
      ->get($index
      ->getEntityTypeId(), $index
      ->bundle());
    $route
      ->addDefaults([
      JsonapiRoutes::RESOURCE_TYPE_KEY => $root_resource_type
        ->getTypeName(),
    ]);
    $routes
      ->add('jsonapi_search_api.index_' . $index
      ->id(), $route);
  }

  // Prefix all routes with the JSON:API route prefix.
  if ($routes
    ->count() > 0) {
    $routes
      ->addPrefix('/%jsonapi%');
    $routes
      ->addRequirements([
      '_access' => 'TRUE',
    ]);
  }
  return $routes;
}