You are here

public function EntityLoad::resolve in GraphQL 8.4

Resolver.

Parameters

string $type:

string $id:

string|null $language:

array|null $bundles:

bool|null $access:

\Drupal\Core\Session\AccountInterface|null $accessUser:

string|null $accessOperation:

\Drupal\graphql\GraphQL\Execution\FieldContext $context:

Return value

\GraphQL\Deferred

File

src/Plugin/GraphQL/DataProducer/Entity/EntityLoad.php, line 146

Class

EntityLoad
Loads a single entity.

Namespace

Drupal\graphql\Plugin\GraphQL\DataProducer\Entity

Code

public function resolve($type, $id, ?string $language, ?array $bundles, ?bool $access, ?AccountInterface $accessUser, ?string $accessOperation, FieldContext $context) {
  $resolver = $this->entityBuffer
    ->add($type, $id);
  return new Deferred(function () use ($type, $language, $bundles, $resolver, $context, $access, $accessUser, $accessOperation) {
    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);
      return NULL;
    }
    $context
      ->addCacheableDependency($entity);
    if (isset($bundles) && !in_array($entity
      ->bundle(), $bundles)) {

      // If the entity is not among the allowed bundles, don't return it.
      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}",
      ]);
    }

    // Check if the passed user (or current user if none is passed) has access
    // to the entity, if not return NULL.
    if ($access) {

      /** @var \Drupal\Core\Access\AccessResultInterface $accessResult */
      $accessResult = $entity
        ->access($accessOperation, $accessUser, TRUE);
      $context
        ->addCacheableDependency($accessResult);
      if (!$accessResult
        ->isAllowed()) {
        return NULL;
      }
    }
    return $entity;
  });
}