View source
<?php
namespace Drupal\thunder_gqls\Plugin\GraphQL\DataProducer;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\graphql\GraphQL\Execution\FieldContext;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use GraphQL\Error\UserError;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class ThunderEntityListProducerBase extends DataProducerPluginBase implements ContainerFactoryPluginInterface {
const MAX_ITEMS = 100;
protected $entityTypeManager;
protected $currentUser;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('current_user'));
}
public function __construct(array $configuration, string $pluginId, array $pluginDefinition, EntityTypeManager $entityTypeManager, AccountInterface $current_user) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->entityTypeManager = $entityTypeManager;
$this->currentUser = $current_user;
}
protected function query(string $type, array $bundles, int $offset, int $limit, array $conditions, array $languages, array $sortBy, FieldContext $cacheContext) : QueryInterface {
if ($limit > static::MAX_ITEMS) {
throw new UserError(sprintf('Exceeded maximum query limit: %s.', static::MAX_ITEMS));
}
$entity_type = $this->entityTypeManager
->getStorage($type);
$query = $entity_type
->getQuery();
$query
->currentRevision()
->accessCheck();
$query
->currentRevision()
->accessCheck(TRUE);
if ($bundles) {
$bundle_key = $entity_type
->getEntityType()
->getKey('bundle');
if (!$bundle_key) {
throw new UserError('No bundles defined for given entity type.');
}
$query
->condition($bundle_key, $bundles, 'IN');
}
if ($languages) {
$query
->condition('langcode', $languages, 'IN');
}
foreach ($conditions as $condition) {
$operation = isset($condition['operator']) ? $condition['operator'] : NULL;
$query
->condition($condition['field'], $condition['value'], $operation);
}
if (!empty($sortBy)) {
foreach ($sortBy as $sort) {
if (!empty($sort['field'])) {
if (!empty($sort['direction']) && strtolower($sort['direction']) == 'desc') {
$direction = 'DESC';
}
else {
$direction = 'ASC';
}
$query
->sort($sort['field'], $direction);
}
}
}
$query
->range($offset, $limit);
$storage = $this->entityTypeManager
->getStorage($type);
$entityType = $storage
->getEntityType();
$cacheContext
->addCacheTags($entityType
->getListCacheTags());
$cacheContext
->addCacheContexts($entityType
->getListCacheContexts());
return $query;
}
}