Query.php 7.9 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Config\Entity\Query;

5
use Drupal\Core\Config\ConfigFactoryInterface;
alexpott's avatar
alexpott committed
6
use Drupal\Core\Entity\EntityTypeInterface;
7
use Drupal\Core\Entity\Query\QueryBase;
8
use Drupal\Core\Entity\Query\QueryInterface;
9
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
10 11 12 13

/**
 * Defines the entity query for configuration entities.
 */
14
class Query extends QueryBase implements QueryInterface {
15

16 17 18 19 20 21 22
  /**
   * Information about the entity type.
   *
   * @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface
   */
  protected $entityType;

23 24 25
  /**
   * The config factory used by the config entity query.
   *
26
   * @var \Drupal\Core\Config\ConfigFactoryInterface
27 28 29
   */
  protected $configFactory;

30 31 32 33 34 35 36
  /**
   * The key value factory.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueFactoryInterface
   */
  protected $keyValueFactory;

37 38 39
  /**
   * Constructs a Query object.
   *
alexpott's avatar
alexpott committed
40 41
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
42 43 44
   * @param string $conjunction
   *   - AND: all of the conditions on the query need to match.
   *   - OR: at least one of the conditions on the query need to match.
45 46
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
47 48
   * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
   *   The key value factory.
49 50
   * @param array $namespaces
   *   List of potential namespaces of the classes belonging to this query.
51
   */
52
  public function __construct(EntityTypeInterface $entity_type, $conjunction, ConfigFactoryInterface $config_factory, KeyValueFactoryInterface $key_value_factory, array $namespaces) {
53
    parent::__construct($entity_type, $conjunction, $namespaces);
54
    $this->configFactory = $config_factory;
55
    $this->keyValueFactory = $key_value_factory;
56 57 58 59 60 61
  }

  /**
   * Overrides \Drupal\Core\Entity\Query\QueryBase::condition().
   *
   * Additional to the syntax defined in the QueryInterface you can use
62
   * placeholders (*) to match all keys of a subarray. Let's take the follow
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
   * yaml file as example:
   * @code
   *  level1:
   *    level2a:
   *      level3: 1
   *    level2b:
   *      level3: 2
   * @endcode
   * Then you can filter out via $query->condition('level1.*.level3', 1).
   */
  public function condition($property, $value = NULL, $operator = NULL, $langcode = NULL) {
    return parent::condition($property, $value, $operator, $langcode);
  }

  /**
78
   * {@inheritdoc}
79 80
   */
  public function execute() {
81 82
    // Load the relevant config records.
    $configs = $this->loadRecords();
83

84
    // Apply conditions.
85 86 87
    $result = $this->condition->compile($configs);

    // Apply sort settings.
88
    foreach ($this->sort as $sort) {
89
      $direction = $sort['direction'] == 'ASC' ? -1 : 1;
90
      $field = $sort['field'];
91
      uasort($result, function ($a, $b) use ($field, $direction) {
92 93 94 95 96 97 98 99
        $properties = explode('.', $field);
        foreach ($properties as $property) {
          if (isset($a[$property]) || isset($b[$property])) {
            $a = isset($a[$property]) ? $a[$property] : NULL;
            $b = isset($b[$property]) ? $b[$property] : NULL;
          }
        }
        return ($a <= $b) ? $direction : -$direction;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
      });
    }

    // Let the pager do its work.
    $this->initializePager();

    if ($this->range) {
      $result = array_slice($result, $this->range['start'], $this->range['length'], TRUE);
    }
    if ($this->count) {
      return count($result);
    }

    // Create the expected structure of entity_id => entity_id. Config
    // entities have string entity IDs.
    foreach ($result as $key => &$value) {
      $value = (string) $key;
    }
    return $result;
  }

121 122 123 124 125 126 127
  /**
   * Loads the config records to examine for the query.
   *
   * @return array
   *   Config records keyed by entity IDs.
   */
  protected function loadRecords() {
alexpott's avatar
alexpott committed
128
    $prefix = $this->entityType->getConfigPrefix() . '.';
129 130
    $prefix_length = strlen($prefix);

131 132
    // Search the conditions for restrictions on configuration object names.
    $names = FALSE;
133 134
    $id_condition = NULL;
    $id_key = $this->entityType->getKey('id');
135
    if ($this->condition->getConjunction() == 'AND') {
136 137 138 139 140 141
      $lookup_keys = $this->entityType->getLookupKeys();
      $conditions = $this->condition->conditions();
      foreach ($conditions as $condition_key => $condition) {
        $operator = $condition['operator'] ?: (is_array($condition['value']) ? 'IN' : '=');
        if (is_string($condition['field']) && ($operator == 'IN' || $operator == '=')) {
          // Special case ID lookups.
142
          if ($condition['field'] == $id_key) {
143 144 145 146
            $ids = (array) $condition['value'];
            $names = array_map(function ($id) use ($prefix) {
              return $prefix . $id;
            }, $ids);
147
          }
148 149 150
          elseif (in_array($condition['field'], $lookup_keys)) {
            // If we don't find anything then there are no matches. No point in
            // listing anything.
151
            $names = [];
152 153 154 155 156 157 158
            $keys = (array) $condition['value'];
            $keys = array_map(function ($value) use ($condition) {
              return $condition['field'] . ':' . $value;
            }, $keys);
            foreach ($this->getConfigKeyStore()->getMultiple($keys) as $list) {
              $names = array_merge($names, $list);
            }
159 160
          }
        }
161 162 163 164 165
        // Save the first ID condition that is not an 'IN' or '=' for narrowing
        // down later.
        elseif (!$id_condition && $condition['field'] == $id_key) {
          $id_condition = $condition;
        }
166 167 168 169 170 171 172 173 174
        // We stop at the first restricting condition on name. In the case where
        // there are additional restricting conditions, results will be
        // eliminated when the conditions are checked on the loaded records.
        if ($names !== FALSE) {
          // If the condition has been responsible for narrowing the list of
          // configuration to check there is no point in checking it further.
          unset($conditions[$condition_key]);
          break;
        }
175 176 177
      }
    }
    // If no restrictions on IDs were found, we need to parse all records.
178
    if ($names === FALSE) {
179
      $names = $this->configFactory->listAll($prefix);
180
    }
181 182 183 184 185 186 187 188 189 190 191 192
    // In case we have an ID condition, try to narrow down the list of config
    // objects to load.
    if ($id_condition && !empty($names)) {
      $value = $id_condition['value'];
      $filter = NULL;
      switch ($id_condition['operator']) {
        case '<>':
          $filter = function ($name) use ($value, $prefix_length) {
            $id = substr($name, $prefix_length);
            return $id !== $value;
          };
          break;
193

194 195 196 197 198 199
        case 'STARTS_WITH':
          $filter = function ($name) use ($value, $prefix_length) {
            $id = substr($name, $prefix_length);
            return strpos($id, $value) === 0;
          };
          break;
200

201 202 203 204 205 206
        case 'CONTAINS':
          $filter = function ($name) use ($value, $prefix_length) {
            $id = substr($name, $prefix_length);
            return strpos($id, $value) !== FALSE;
          };
          break;
207

208 209 210 211 212 213 214 215 216 217 218
        case 'ENDS_WITH':
          $filter = function ($name) use ($value, $prefix_length) {
            $id = substr($name, $prefix_length);
            return strrpos($id, $value) === strlen($id) - strlen($value);
          };
          break;
      }
      if ($filter) {
        $names = array_filter($names, $filter);
      }
    }
219 220

    // Load the corresponding records.
221
    $records = [];
222 223 224 225 226 227
    foreach ($this->configFactory->loadMultiple($names) as $config) {
      $records[substr($config->getName(), $prefix_length)] = $config->get();
    }
    return $records;
  }

228 229 230 231 232 233 234 235 236 237
  /**
   * Gets the key value store used to store fast lookups.
   *
   * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   *   The key value store used to store fast lookups.
   */
  protected function getConfigKeyStore() {
    return $this->keyValueFactory->get(QueryFactory::CONFIG_LOOKUP_PREFIX . $this->entityTypeId);
  }

238
}