3 namespace Drupal\Core\Entity\KeyValueStore\Query;
5 use Drupal\Core\Entity\EntityTypeInterface;
6 use Drupal\Core\Entity\Query\QueryBase;
7 use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
10 * Defines the entity query for entities stored in a key value backend.
12 class Query extends QueryBase {
15 * The key value factory.
17 * @var \Drupal\Core\KeyValueStore\KeyValueFactoryInterface
19 protected $keyValueFactory;
22 * Constructs a new Query.
24 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
26 * @param string $conjunction
27 * - AND: all of the conditions on the query need to match.
28 * - OR: at least one of the conditions on the query need to match.
29 * @param array $namespaces
30 * List of potential namespaces of the classes belonging to this query.
31 * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
32 * The key value factory.
34 public function __construct(EntityTypeInterface $entity_type, $conjunction, array $namespaces, KeyValueFactoryInterface $key_value_factory) {
35 parent::__construct($entity_type, $conjunction, $namespaces);
36 $this->keyValueFactory = $key_value_factory;
42 public function execute() {
43 // Load the relevant records.
44 $records = $this->keyValueFactory->get('entity_storage__' . $this->entityTypeId)->getAll();
47 $result = $this->condition->compile($records);
49 // Apply sort settings.
50 foreach ($this->sort as $sort) {
51 $direction = $sort['direction'] == 'ASC' ? -1 : 1;
52 $field = $sort['field'];
53 uasort($result, function ($a, $b) use ($field, $direction) {
54 return ($a[$field] <= $b[$field]) ? $direction : -$direction;
58 // Let the pager do its work.
59 $this->initializePager();
62 $result = array_slice($result, $this->range['start'], $this->range['length'], TRUE);
65 return count($result);
68 // Create the expected structure of entity_id => entity_id.
69 $entity_ids = array_keys($result);
70 return array_combine($entity_ids, $entity_ids);