You are here

class ConfigEntityQuery in Configuration Views 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/views/query/ConfigEntityQuery.php \Drupal\config_views\Plugin\views\query\ConfigEntityQuery

This query is able to work with config entities.

Plugin annotation


@ViewsQuery(
  id = "views_config_entity_query",
  title = @Translation("Entity Query"),
  help = @Translation("Query will be generated and run using the Drupal Entity Query API.")
)

Hierarchy

Expanded class hierarchy of ConfigEntityQuery

File

src/Plugin/views/query/ConfigEntityQuery.php, line 20

Namespace

Drupal\config_views\Plugin\views\query
View source
class ConfigEntityQuery extends Sql {
  protected $commands = [];
  protected $entityConditionGroups;
  protected $sorting = [];

  /**
   * {@inheritdoc}
   */
  public function ensureTable($table, $relationship = NULL, JoinPluginBase $join = NULL) {
  }

  /**
   * {@inheritdoc}
   */
  public function addField($table, $field, $alias = '', $params = []) {
    return $alias ? $alias : $field;
  }

  /**
   * Adds a condition.
   */
  public function condition($group, $field, $value = NULL, $operator = NULL, $langcode = NULL) {
    $this->commands[$group][] = [
      'method' => 'condition',
      'args' => [
        $field,
        $value,
        $operator,
        $langcode,
      ],
    ];
  }

  /**
   * Add's an exists command.
   */
  public function exists($group, $field, $langcode = NULL) {
    $this->commands[$group][] = [
      'method' => 'exists',
      'args' => [
        $field,
        $langcode,
      ],
    ];
  }

  /**
   * Add's an not exists command.
   */
  public function notExists($group, $field, $langcode = NULL) {
    $this->commands[$group][] = [
      'method' => 'notExists',
      'args' => [
        $field,
        $langcode,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function build(ViewExecutable $view) {

    // Store the view in the object to be able to use it later.
    $this->view = $view;
    $view
      ->initPager();
  }

  /**
   * {@inheritdoc}
   */
  public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = []) {
    if ($alias) {
      $this->sorting[$alias] = $order;
    }
    elseif ($field) {
      $this->sorting[$field] = $order;
    }
  }

  /**
   * Executes query and fills the associated view object with according values.
   *
   * Values to set: $view->result, $view->total_rows, $view->execute_time,
   * $view->pager['current_page'].
   *
   * $view->result should contain an array of objects. The array must use a
   * numeric index starting at 0.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   The view which is executed.
   */
  public function execute(ViewExecutable $view) {
    $this->group_operator = isset($this->group_operator) ? $this->group_operator : 'AND';
    $base_table = $this->view->storage
      ->get('base_table');
    $data = \Drupal::service('views.views_data')
      ->get($base_table);
    $entity_type = $data['table']['entity type'];
    $query = \Drupal::entityQuery($entity_type, $this->group_operator);
    $this->entityConditionGroups = [
      $query,
    ];
    $this
      ->buildConditions();
    $this
      ->buildSorting($query);
    $ids = $query
      ->execute();
    $results = \Drupal::entityTypeManager()
      ->getStorage($entity_type)
      ->loadMultiple($ids);
    $index = 0;

    /* @var \Drupal\Core\Config\Entity\ConfigEntityBase $result */
    foreach ($results as $result) {

      // @todo: toArray() doesn't return all properties.
      $entity = $result
        ->toArray();
      $entity['type'] = $entity_type;
      $entity['entity'] = $result;

      // 'index' key is required.
      $entity['index'] = $index++;
      $view->result[] = new ResultRow($entity);
    }
    $view->total_rows = count($view->result);
    $view->execute_time = 0;
  }

  /**
   * Build conditions based on it's groups.
   */
  protected function buildConditions() {
    foreach ($this->commands as $group => $grouped_commands) {
      $conditionGroup = $this
        ->getConditionGroup($group);
      foreach ($grouped_commands as $command) {
        call_user_func_array([
          $conditionGroup,
          $command['method'],
        ], $command['args']);
      }
    }
  }

  /**
   * Returns a condition group.
   */
  protected function getConditionGroup($group) {
    if (!isset($this->entityConditionGroups[$group])) {
      $query = $this->entityConditionGroups[0];
      $condition = isset($this->where[$group]) && $this->where[$group]['type'] == 'OR' ? $query
        ->orConditionGroup() : $query
        ->andConditionGroup();
      $query
        ->condition($condition);
      $this->entityConditionGroups[$group] = $condition;
    }
    return $this->entityConditionGroups[$group];
  }

  /**
   * Adds sorting to query.
   *
   * @param \Drupal\Core\Entity\Query\QueryInterface $query
   *   The query to get configs.
   */
  protected function buildSorting(QueryInterface $query) {
    foreach ($this->sorting as $field => $direction) {
      $query
        ->sort($field, $direction);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigEntityQuery::$commands protected property
ConfigEntityQuery::$entityConditionGroups protected property
ConfigEntityQuery::$sorting protected property
ConfigEntityQuery::addField public function Add a field to the query table, possibly with an alias. This will automatically call ensureTable to make sure the required table exists, *unless* $table is unset. Overrides Sql::addField
ConfigEntityQuery::addOrderBy public function Add an ORDER BY clause to the query. Overrides Sql::addOrderBy
ConfigEntityQuery::build public function Builds the necessary info to execute the query. Overrides Sql::build
ConfigEntityQuery::buildConditions protected function Build conditions based on it's groups.
ConfigEntityQuery::buildSorting protected function Adds sorting to query.
ConfigEntityQuery::condition public function Adds a condition.
ConfigEntityQuery::ensureTable public function Ensure a table exists in the queue; if it already exists it won't do anything, but if it doesn't it will add the table queue. It will ensure a path leads back to the relationship table. Overrides Sql::ensureTable
ConfigEntityQuery::execute public function Executes query and fills the associated view object with according values. Overrides Sql::execute
ConfigEntityQuery::exists public function Add's an exists command.
ConfigEntityQuery::getConditionGroup protected function Returns a condition group.
ConfigEntityQuery::notExists public function Add's an not exists command.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. 8
PluginBase::$view public property The top object of a view. 1
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 6
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::validate public function Validate that the plugin is correct and can be saved. Overrides ViewsPluginInterface::validate 6
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
QueryPluginBase::$limit protected property Stores the limit of items that should be requested in the query.
QueryPluginBase::$pager public property A pager plugin that should be provided by the display.
QueryPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginBase::calculateDependencies 1
QueryPluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
QueryPluginBase::getEntityTableInfo public function Returns an array of all tables from the query that map to an entity type.
QueryPluginBase::getLimit public function Returns the limit of the query.
QueryPluginBase::getTimezoneOffset public function Get the timezone offset in seconds.
QueryPluginBase::setGroupOperator public function Control how all WHERE and HAVING groups are put together.
QueryPluginBase::setLimit public function Set a LIMIT on the query, specifying a maximum number of results.
QueryPluginBase::setOffset public function Set an OFFSET on the query, specifying a number of results to skip
QueryPluginBase::setWhereGroup public function Create a new grouping for the WHERE or HAVING clause.
QueryPluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides PluginBase::summaryTitle
QueryPluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm
Sql::$dateSql protected property The database-specific date handler.
Sql::$distinct public property A flag as to whether or not to make the primary field distinct.
Sql::$entityTypeManager protected property The entity type manager.
Sql::$fieldAliases protected property An array mapping table aliases and field names to field aliases.
Sql::$fields public property An array of fields.
Sql::$getCountOptimized protected property Should this query be optimized for counts, for example no sorts.
Sql::$groupby public property A simple array of group by clauses.
Sql::$groupOperator protected property The default operator to use when connecting the WHERE groups. May be AND or OR.
Sql::$hasAggregate protected property
Sql::$having public property An array of sections of the HAVING query. Each section is in itself an array of pieces and a flag as to whether or not it should be AND or OR.
Sql::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
Sql::$noDistinct protected property Is the view marked as not distinct.
Sql::$orderby public property A simple array of order by clauses.
Sql::$relationships public property Holds an array of relationships, which are aliases of the primary table that represent different ways to join the same table in.
Sql::$tableQueue protected property A list of tables in the order they should be added, keyed by alias.
Sql::$tables public property Holds an array of tables and counts added so that we can create aliases
Sql::$tags public property Query tags which will be passed over to the dbtng query object.
Sql::$where public property An array of sections of the WHERE query. Each section is in itself an array of pieces and a flag as to whether or not it should be AND or OR.
Sql::addGroupBy public function Add a simple GROUP BY clause to the query. The caller is responsible for ensuring that the fields are fully qualified and the table is properly added.
Sql::addHavingExpression public function Add a complex HAVING clause to the query. The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist in the query. Internally the dbtng method…
Sql::addRelationship public function A relationship is an alternative endpoint to a series of table joins. Relationships must be aliases of the primary table and they must join either to the primary table or to a pre-existing relationship.
Sql::addSignature public function Add a signature to the query, if such a thing is feasible. Overrides QueryPluginBase::addSignature
Sql::addTable public function Add a table to the query, ensuring the path exists.
Sql::addTag public function Adds a query tag to the sql object.
Sql::addWhere public function Add a simple WHERE clause to the query. The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.
Sql::addWhereExpression public function Add a complex WHERE clause to the query.
Sql::adjustJoin protected function Fix a join to adhere to the proper relationship; the left table can vary based upon what relationship items are joined in on.
Sql::aggregationMethodDistinct public function
Sql::aggregationMethodSimple public function
Sql::alter public function Let modules modify the query just prior to finalizing it. Overrides QueryPluginBase::alter
Sql::assignEntitiesToResult protected function Sets entities onto the view result row objects.
Sql::buildCondition protected function Construct the "WHERE" or "HAVING" part of the query.
Sql::buildOptionsForm public function Add settings for the ui. Overrides PluginBase::buildOptionsForm
Sql::clearFields public function Remove all fields that may've been added; primarily used for summary mode where we're changing the query because we didn't get data we needed.
Sql::compileFields protected function Adds fields to the query.
Sql::create public static function Creates an instance of the plugin. Overrides PluginBase::create
Sql::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides PluginBase::defineOptions
Sql::ensurePath protected function Make sure that the specified table can be properly linked to the primary table in the JOINs. This function uses recursion. If the tables needed to complete the path back to the primary table are not in the query they will be added, but additional…
Sql::getAggregationInfo public function Get aggregation info for group by queries. Overrides QueryPluginBase::getAggregationInfo
Sql::getAllEntities protected function Gets all the involved entities of the view.
Sql::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides QueryPluginBase::getCacheMaxAge
Sql::getCacheTags public function The cache tags associated with this object. Overrides QueryPluginBase::getCacheTags
Sql::getDateField public function Returns a Unix timestamp to database native timestamp expression. Overrides QueryPluginBase::getDateField
Sql::getDateFormat public function Creates cross-database date formatting. Overrides QueryPluginBase::getDateFormat
Sql::getFieldAlias protected function Returns the alias for the given field added to $table.
Sql::getJoinData public function Retrieve join data from the larger join data cache.
Sql::getNonAggregates protected function Returns a list of non-aggregates to be added to the "group by" clause.
Sql::getTableInfo public function Get the information associated with a table.
Sql::getTableQueue public function Returns a reference to the table queue array for this query.
Sql::getWhereArgs public function Get the arguments attached to the WHERE and HAVING clauses of this query.
Sql::init public function Initialize the plugin. Overrides PluginBase::init
Sql::loadEntities public function Loads all entities contained in the passed-in $results. . If the entity belongs to the base table, then it gets stored in $result->_entity. Otherwise, it gets stored in $result->_relationship_entities[$relationship_id]; Overrides QueryPluginBase::loadEntities
Sql::markTable protected function
Sql::placeholder public function Generates a unique placeholder used in the db query.
Sql::query public function Generate a query and a countquery from all of the information supplied to the object. Overrides QueryPluginBase::query
Sql::queueTable public function Add a table to the query without ensuring the path.
Sql::setCountField public function Set what field the query will count() on for paging.
Sql::setDistinct protected function Set the view to be distinct (per base field).
Sql::setFieldTimezoneOffset public function Applies a timezone offset to the given field. Overrides QueryPluginBase::setFieldTimezoneOffset
Sql::setupTimezone public function Set the database to the current user timezone. Overrides QueryPluginBase::setupTimezone
Sql::submitOptionsForm public function Special submit handling. Overrides QueryPluginBase::submitOptionsForm
Sql::__construct public function Constructs a Sql object. Overrides PluginBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.