ImageDerivative.php in GraphQL 8.4
File
src/Plugin/GraphQL/DataProducer/Entity/Fields/Image/ImageDerivative.php
View source
<?php
namespace Drupal\graphql\Plugin\GraphQL\DataProducer\Entity\Fields\Image;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\file\FileInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\image\Entity\ImageStyle;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ImageDerivative extends DataProducerPluginBase implements ContainerFactoryPluginInterface {
protected $renderer;
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static($configuration, $pluginId, $pluginDefinition, $container
->get('renderer'));
}
public function __construct(array $configuration, $pluginId, $pluginDefinition, RendererInterface $renderer) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->renderer = $renderer;
}
public function resolve(FileInterface $entity = NULL, $style, RefinableCacheableDependencyInterface $metadata) {
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)) {
$image = \Drupal::service('image.factory')
->get($entity
->getFileUri());
if ($image
->isValid()) {
$width = $image
->getWidth();
$height = $image
->getHeight();
}
}
$dimensions = [
'width' => $width,
'height' => $height,
];
$image_style
->transformDimensions($dimensions, $entity
->getFileUri());
$metadata
->addCacheableDependency($image_style);
$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;
}
}