Query.php 2.2 KB

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