You are here

public function EntryPoint::index in JSON:API 8

Same name and namespace in other branches
  1. 8.2 src/Controller/EntryPoint.php \Drupal\jsonapi\Controller\EntryPoint::index()

Controller to list all the resources.

Return value

\Drupal\Core\Cache\CacheableJsonResponse The response object.

File

src/Controller/EntryPoint.php, line 64

Class

EntryPoint
Controller for the API entry point.

Namespace

Drupal\jsonapi\Controller

Code

public function index() {

  // Execute the request in context so the cacheable metadata from the entity
  // grants system is caught and added to the response. This is surfaced when
  // executing the underlying entity query.
  $context = new RenderContext();

  /** @var \Drupal\Core\Cache\CacheableResponseInterface $response */
  $do_build_urls = function () {
    $self = Url::fromRoute('jsonapi.resource_list')
      ->setAbsolute();

    // Only build URLs for exposed resources.
    $resources = array_filter($this->resourceTypeRepository
      ->all(), function ($resource) {
      return !$resource
        ->isInternal();
    });
    return array_reduce($resources, function (array $carry, ResourceType $resource_type) {

      // TODO: Learn how to invalidate the cache for this page when a new
      // entity type or bundle gets added, removed or updated.
      // $this->response->addCacheableDependency($definition);
      $url = Url::fromRoute(sprintf('jsonapi.%s.collection', $resource_type
        ->getTypeName()))
        ->setAbsolute();
      $carry[$resource_type
        ->getTypeName()] = $url
        ->toString();
      return $carry;
    }, [
      'self' => $self
        ->toString(),
    ]);
  };
  $urls = $this->renderer
    ->executeInRenderContext($context, $do_build_urls);
  $json_response = new CacheableJsonResponse([
    'data' => [],
    'links' => $urls,
  ]);
  if (!$context
    ->isEmpty()) {
    $json_response
      ->addCacheableDependency($context
      ->pop());
  }
  return $json_response;
}