You are here

public function ImageDerivative::resolve in GraphQL 8.4

Resolver.

Parameters

\Drupal\file\FileInterface $entity:

string $style:

\Drupal\Core\Cache\RefinableCacheableDependencyInterface $metadata:

Return value

array|null

File

src/Plugin/GraphQL/DataProducer/Entity/Fields/Image/ImageDerivative.php, line 91

Class

ImageDerivative
Returns an image style derivative of an image.

Namespace

Drupal\graphql\Plugin\GraphQL\DataProducer\Entity\Fields\Image

Code

public function resolve(FileInterface $entity = NULL, $style, RefinableCacheableDependencyInterface $metadata) {

  // Return if we dont have an entity.
  if (!$entity) {
    return NULL;
  }
  $access = $entity
    ->access('view', NULL, TRUE);
  $metadata
    ->addCacheableDependency($access);
  if ($access
    ->isAllowed() && ($image_style = ImageStyle::load($style))) {
    $width = $entity->width;
    $height = $entity->height;
    if (empty($width) || empty($height)) {

      /** @var \Drupal\Core\Image\ImageInterface $image */
      $image = \Drupal::service('image.factory')
        ->get($entity
        ->getFileUri());
      if ($image
        ->isValid()) {
        $width = $image
          ->getWidth();
        $height = $image
          ->getHeight();
      }
    }

    // Determine the dimensions of the styled image.
    $dimensions = [
      'width' => $width,
      'height' => $height,
    ];
    $image_style
      ->transformDimensions($dimensions, $entity
      ->getFileUri());
    $metadata
      ->addCacheableDependency($image_style);

    // The underlying URL generator that will be invoked will leak cache
    // metadata, resulting in an exception. By wrapping within a new render
    // context, we can capture the leaked metadata and make sure it gets
    // incorporated into the response.
    $context = new RenderContext();
    $url = $this->renderer
      ->executeInRenderContext($context, function () use ($image_style, $entity) {
      return $image_style
        ->buildUrl($entity
        ->getFileUri());
    });
    if (!$context
      ->isEmpty()) {
      $metadata
        ->addCacheableDependency($context
        ->pop());
    }
    return [
      'url' => $url,
      'width' => $dimensions['width'],
      'height' => $dimensions['height'],
    ];
  }
  return NULL;
}