You are here

public function RouteEntity::resolve in GraphQL 8.4

Resolver.

Parameters

\Drupal\Core\Url|mixed $url: The URL to get the route entity from.

string|null $language: The language code to get a translation of the entity.

\Drupal\graphql\GraphQL\Execution\FieldContext $context: The GraphQL field context.

File

src/Plugin/GraphQL/DataProducer/Routing/RouteEntity.php, line 108

Class

RouteEntity
Loads the entity associated with the current URL.

Namespace

Drupal\graphql\Plugin\GraphQL\DataProducer\Routing

Code

public function resolve($url, ?string $language, FieldContext $context) : ?Deferred {
  if ($url instanceof Url) {
    list(, $type) = explode('.', $url
      ->getRouteName());
    $parameters = $url
      ->getRouteParameters();
    $id = $parameters[$type];
    $resolver = $this->entityBuffer
      ->add($type, $id);
    return new Deferred(function () use ($type, $resolver, $context, $language) {
      if (!($entity = $resolver())) {

        // If there is no entity with this id, add the list cache tags so that
        // the cache entry is purged whenever a new entity of this type is
        // saved.
        $type = $this->entityTypeManager
          ->getDefinition($type);

        /** @var \Drupal\Core\Entity\EntityTypeInterface $type */
        $tags = $type
          ->getListCacheTags();
        $context
          ->addCacheTags($tags)
          ->addCacheTags([
          '4xx-response',
        ]);
        return NULL;
      }

      // Get the correct translation.
      if (isset($language) && $language != $entity
        ->language()
        ->getId() && $entity instanceof TranslatableInterface) {
        $entity = $entity
          ->getTranslation($language);
        $entity
          ->addCacheContexts([
          "static:language:{$language}",
        ]);
      }
      $access = $entity
        ->access('view', NULL, TRUE);
      $context
        ->addCacheableDependency($access);
      if ($access
        ->isAllowed()) {
        return $entity;
      }
      return NULL;
    });
  }
  return NULL;
}