From 8a07c232e0ebfece33eefa9e1277f656fb140f57 Mon Sep 17 00:00:00 2001 From: Daniel Bosen Date: Tue, 20 Aug 2024 11:34:43 +0200 Subject: [PATCH] refactor EntityListResponse --- .../src/Wrappers/EntityListResponse.php | 48 ++++++++++++++++--- 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/modules/thunder_gqls/src/Wrappers/EntityListResponse.php b/modules/thunder_gqls/src/Wrappers/EntityListResponse.php index 44ef51d07..703e1b10e 100644 --- a/modules/thunder_gqls/src/Wrappers/EntityListResponse.php +++ b/modules/thunder_gqls/src/Wrappers/EntityListResponse.php @@ -2,29 +2,62 @@ namespace Drupal\thunder_gqls\Wrappers; +use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\Entity\Query\QueryInterface; +use Drupal\graphql\GraphQL\Buffers\EntityBuffer; use GraphQL\Deferred; +use Symfony\Component\DependencyInjection\ContainerInterface; /** * The thunder entity list response class. */ -class EntityListResponse implements EntityListResponseInterface { +class EntityListResponse implements EntityListResponseInterface, ContainerInjectionInterface { /** * The query interface. * * @var \Drupal\Core\Entity\Query\QueryInterface */ - protected $query; + protected QueryInterface $query; + + /** + * The entity buffer. + * + * @var \Drupal\graphql\GraphQL\Buffers\EntityBuffer + */ + private EntityBuffer $buffer; /** * EntityListResponse constructor. * + * @param \Drupal\Core\Entity\Query\QueryInterface|\Drupal\graphql\GraphQL\Buffers\EntityBuffer $parameter + */ + public function __construct(QueryInterface|EntityBuffer $parameter) { + if ($parameter instanceof QueryInterface) { + $this->setQuery($parameter); + return; + } + $this->buffer = $parameter; + } + + /** + * {@inheritDoc} + */ + public static function create(ContainerInterface $container): self { + return new static( + $container->get('graphql.buffer.entity'), + ); + } + + /** + * Set query. + * * @param \Drupal\Core\Entity\Query\QueryInterface $query - * The query interface. + * The query. */ - public function __construct(QueryInterface $query) { + public function setQuery(QueryInterface $query): EntityListResponse { $this->query = $query; + return $this; } /** @@ -51,8 +84,11 @@ public function items() { return []; } - $buffer = \Drupal::service('graphql.buffer.entity'); - $callback = $buffer->add($this->query->getEntityTypeId(), array_values($result)); + if (empty($this->buffer)) { + $this->buffer = \Drupal::service('graphql.buffer.entity'); + } + + $callback = $this->buffer->add($this->query->getEntityTypeId(), array_values($result)); return new Deferred(fn() => $callback()); }