EntityRendered.php in GraphQL 8.4
File
src/Plugin/GraphQL/DataProducer/Entity/EntityRendered.php
View source
<?php
namespace Drupal\graphql\Plugin\GraphQL\DataProducer\Entity;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityRendered extends DataProducerPluginBase implements ContainerFactoryPluginInterface {
use DependencySerializationTrait;
protected $entityTypeManager;
protected $renderer;
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static($configuration, $pluginId, $pluginDefinition, $container
->get('entity_type.manager'), $container
->get('renderer'));
}
public function __construct(array $configuration, $pluginId, $pluginDefinition, EntityTypeManagerInterface $entityTypeManager, RendererInterface $renderer) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->entityTypeManager = $entityTypeManager;
$this->renderer = $renderer;
}
public function resolve(EntityInterface $entity, $mode, RefinableCacheableDependencyInterface $metadata) {
$mode = $mode ?? 'full';
$builder = $this->entityTypeManager
->getViewBuilder($entity
->getEntityTypeId());
$view = $builder
->view($entity, $mode, $entity
->language()
->getId());
$context = new RenderContext();
$result = $this->renderer
->executeInRenderContext($context, function () use ($view) {
return $this->renderer
->render($view);
});
if (!$context
->isEmpty()) {
$metadata
->addCacheableDependency($context
->pop());
}
return (string) $result;
}
}