ThunderImage.php in Thunder 6.2.x
File
modules/thunder_gqls/src/Plugin/GraphQL/DataProducer/ThunderImage.php
View source
<?php
namespace Drupal\thunder_gqls\Plugin\GraphQL\DataProducer;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Image\ImageFactory;
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 Symfony\Component\DependencyInjection\ContainerInterface;
class ThunderImage extends DataProducerPluginBase implements ContainerFactoryPluginInterface {
protected $renderer;
protected $imageFactory;
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static($configuration, $pluginId, $pluginDefinition, $container
->get('renderer'), $container
->get('image.factory'));
}
public function __construct(array $configuration, $pluginId, $pluginDefinition, RendererInterface $renderer, ImageFactory $imageFactory) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->renderer = $renderer;
$this->imageFactory = $imageFactory;
}
public function resolve(FileInterface $entity, array $field, RefinableCacheableDependencyInterface $metadata) {
$access = $entity
->access('view', NULL, TRUE);
$metadata
->addCacheableDependency($access);
if ($access
->isAllowed()) {
$context = new RenderContext();
$imageFactory = $this->imageFactory;
$data = $this->renderer
->executeInRenderContext($context, function () use ($entity, $imageFactory, $field) {
$uri = $entity
->getFileUri();
$image = $imageFactory
->get($uri);
$current_field = reset($field);
return [
'src' => file_create_url($uri),
'width' => $image
->getWidth(),
'height' => $image
->getHeight(),
'alt' => $current_field['alt'],
'title' => $current_field['title'],
];
});
if (!$context
->isEmpty()) {
$metadata
->addCacheableDependency($context
->pop());
}
return $data;
}
return [];
}
}