class QueryPluginBase

Same name in other branches
  1. 8.9.x core/modules/views/src/Plugin/views/query/QueryPluginBase.php \Drupal\views\Plugin\views\query\QueryPluginBase
  2. 10 core/modules/views/src/Plugin/views/query/QueryPluginBase.php \Drupal\views\Plugin\views\query\QueryPluginBase
  3. 11.x core/modules/views/src/Plugin/views/query/QueryPluginBase.php \Drupal\views\Plugin\views\query\QueryPluginBase

Base plugin class for Views queries.

Hierarchy

Expanded class hierarchy of QueryPluginBase

Related topics

12 files declare their use of QueryPluginBase
content_moderation_test_views.module in core/modules/content_moderation/tests/modules/content_moderation_test_views/content_moderation_test_views.module
Module file for the content moderation test views module.
DisplayKernelTest.php in core/modules/views/tests/src/Kernel/Plugin/DisplayKernelTest.php
EntityFieldRenderer.php in core/modules/views/src/Entity/Render/EntityFieldRenderer.php
EntityTranslationRendererBase.php in core/modules/views/src/Entity/Render/EntityTranslationRendererBase.php
QueryTest.php in core/modules/views/tests/modules/views_test_data/src/Plugin/views/query/QueryTest.php

... See full list

File

core/modules/views/src/Plugin/views/query/QueryPluginBase.php, line 34

Namespace

Drupal\views\Plugin\views\query
View source
abstract class QueryPluginBase extends PluginBase implements CacheableDependencyInterface {
    
    /**
     * A pager plugin that should be provided by the display.
     *
     * @var \Drupal\views\Plugin\views\pager\PagerPluginBase|null
     */
    public $pager = NULL;
    
    /**
     * Stores the limit of items that should be requested in the query.
     *
     * @var int
     */
    protected $limit;
    
    /**
     * Controls how the WHERE and HAVING groups are put together.
     *
     * @var string
     */
    protected $groupOperator;
    
    /**
     * Generate a query and a countquery from all of the information supplied.
     *
     * @param $get_count
     *   Provide a countquery if this is true, otherwise provide a normal query.
     */
    public function query($get_count = FALSE) {
    }
    
    /**
     * Let modules modify the query just prior to finalizing it.
     *
     * @param \Drupal\views\ViewExecutable $view
     *   The view which is executed.
     */
    public function alter(ViewExecutable $view) {
    }
    
    /**
     * Builds the necessary info to execute the query.
     *
     * @param \Drupal\views\ViewExecutable $view
     *   The view which is executed.
     */
    public function build(ViewExecutable $view) {
    }
    
    /**
     * Executes query and fills 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) {
    }
    
    /**
     * Add a signature to the query, if such a thing is feasible.
     *
     * This signature is something that can be used when perusing query logs to
     * discern where particular queries might be coming from.
     *
     * @param \Drupal\views\ViewExecutable $view
     *   The view which is executed.
     */
    public function addSignature(ViewExecutable $view) {
    }
    
    /**
     * Get aggregation info for group by queries.
     *
     * If NULL, aggregation is not allowed.
     */
    public function getAggregationInfo() {
    }
    public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    }
    public function submitOptionsForm(&$form, FormStateInterface $form_state) {
    }
    public function summaryTitle() {
        return $this->t('Settings');
    }
    
    /**
     * {@inheritdoc}
     */
    public function calculateDependencies() {
        $dependencies = [];
        foreach ($this->getEntityTableInfo() as $info) {
            if (!empty($info['provider'])) {
                $dependencies['module'][] = $info['provider'];
            }
        }
        return $dependencies;
    }
    
    /**
     * Set a LIMIT on the query, specifying a maximum number of results.
     */
    public function setLimit($limit) {
        $this->limit = $limit;
    }
    
    /**
     * Set an OFFSET on the query, specifying a number of results to skip.
     */
    public function setOffset($offset) {
        $this->offset = $offset;
    }
    
    /**
     * Returns the limit of the query.
     */
    public function getLimit() {
        return $this->limit;
    }
    
    /**
     * Create a new grouping for the WHERE or HAVING clause.
     *
     * @param $type
     *   Either 'AND' or 'OR'. All items within this group will be added
     *   to the WHERE clause with this logical operator.
     * @param $group
     *   An ID to use for this group. If unspecified, an ID will be generated.
     * @param $where
     *   'where' or 'having'.
     *
     * @return int|string
     *   The group ID generated.
     */
    public function setWhereGroup($type = 'AND', $group = NULL, $where = 'where') {
        // Set an alias.
        $groups =& $this->{$where};
        if (!isset($group)) {
            $group = empty($groups) ? 1 : max(array_keys($groups)) + 1;
        }
        // Create an empty group
        if (empty($groups[$group])) {
            $groups[$group] = [
                'conditions' => [],
                'args' => [],
            ];
        }
        $groups[$group]['type'] = strtoupper($type);
        return $group;
    }
    
    /**
     * Control how all WHERE and HAVING groups are put together.
     *
     * @param $type
     *   Either 'AND' or 'OR'
     */
    public function setGroupOperator($type = 'AND') {
        $this->groupOperator = strtoupper($type);
    }
    
    /**
     * 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];
     *
     * Query plugins that don't support entities can leave the method empty.
     */
    public function loadEntities(&$results) {
    }
    
    /**
     * Returns a Unix timestamp to database native timestamp expression.
     *
     * @param string $field
     *   The query field that will be used in the expression.
     * @param bool $string_date
     *   For certain databases, date format functions vary depending on string or
     *   numeric storage.
     * @param bool $calculate_offset
     *   If set to TRUE, the timezone offset will be included in the returned
     *   field.
     *
     * @return string
     *   An expression representing a timestamp with time zone.
     */
    public function getDateField($field, $string_date = FALSE, $calculate_offset = TRUE) {
        return $field;
    }
    
    /**
     * Set the database to the current user timezone.
     *
     * @return string
     *   The current timezone as returned by date_default_timezone_get().
     */
    public function setupTimezone() {
        return date_default_timezone_get();
    }
    
    /**
     * Creates cross-database date formatting.
     *
     * @param string $field
     *   An appropriate query expression pointing to the date field.
     * @param string $format
     *   A format string for the result, like 'Y-m-d H:i:s'.
     * @param bool $string_date
     *   For certain databases, date format functions vary depending on string or
     *   numeric storage.
     *
     * @return string
     *   A string representing the field formatted as a date in the format
     *   specified by $format.
     */
    public function getDateFormat($field, $format, $string_date = FALSE) {
        return $field;
    }
    
    /**
     * Returns an array of all tables from the query that map to an entity type.
     *
     * Includes the base table and all relationships, if eligible.
     *
     * Available keys for each table:
     * - base: The actual base table (i.e. "user" for an author relationship).
     * - relationship_id: The id of the relationship, or "none".
     * - alias: The alias used for the relationship.
     * - entity_type: The entity type matching the base table.
     * - revision: A boolean that specifies whether the table is a base table or
     *   a revision table of the entity type.
     *
     * @return array
     *   An array of table information, keyed by table alias.
     */
    public function getEntityTableInfo() {
        // Start with the base table.
        $entity_tables = [];
        $views_data = Views::viewsData();
        $base_table = $this->view->storage
            ->get('base_table');
        $base_table_data = $views_data->get($base_table);
        if (isset($base_table_data['table']['entity type'])) {
            $entity_tables[$base_table_data['table']['entity type']] = [
                'base' => $base_table,
                'alias' => $base_table,
                'relationship_id' => 'none',
                'entity_type' => $base_table_data['table']['entity type'],
                'revision' => $base_table_data['table']['entity revision'],
            ];
            // Include the entity provider.
            if (!empty($base_table_data['table']['provider'])) {
                $entity_tables[$base_table_data['table']['entity type']]['provider'] = $base_table_data['table']['provider'];
            }
        }
        // Include all relationships.
        foreach ((array) $this->view->relationship as $relationship_id => $relationship) {
            $table_data = $views_data->get($relationship->definition['base']);
            if (isset($table_data['table']['entity type'])) {
                // If this is not one of the entity base tables, skip it.
                $entity_type = \Drupal::entityTypeManager()->getDefinition($table_data['table']['entity type']);
                $entity_base_tables = [
                    $entity_type->getBaseTable(),
                    $entity_type->getDataTable(),
                    $entity_type->getRevisionTable(),
                    $entity_type->getRevisionDataTable(),
                ];
                if (!in_array($relationship->definition['base'], $entity_base_tables)) {
                    continue;
                }
                $entity_tables[$relationship_id . '__' . $relationship->tableAlias] = [
                    'base' => $relationship->definition['base'],
                    'relationship_id' => $relationship_id,
                    'alias' => $relationship->alias,
                    'entity_type' => $table_data['table']['entity type'],
                    'revision' => $table_data['table']['entity revision'],
                ];
                // Include the entity provider.
                if (!empty($table_data['table']['provider'])) {
                    $entity_tables[$relationship_id . '__' . $relationship->tableAlias]['provider'] = $table_data['table']['provider'];
                }
            }
        }
        // Determine which of the tables are revision tables.
        foreach ($entity_tables as $table_alias => $table) {
            $entity_type = \Drupal::entityTypeManager()->getDefinition($table['entity_type']);
            if ($entity_type->getRevisionTable() == $table['base']) {
                $entity_tables[$table_alias]['revision'] = TRUE;
            }
        }
        return $entity_tables;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCacheMaxAge() {
        return Cache::PERMANENT;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCacheContexts() {
        $contexts = [];
        if (($views_data = Views::viewsData()->get($this->view->storage
            ->get('base_table'))) && !empty($views_data['table']['entity type'])) {
            $entity_type_id = $views_data['table']['entity type'];
            $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
            $contexts = $entity_type->getListCacheContexts();
        }
        return $contexts;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCacheTags() {
        return [];
    }
    
    /**
     * Applies a timezone offset to the given field.
     *
     * @param string &$field
     *   The date field, in string format.
     * @param int $offset
     *   The timezone offset to apply to the field.
     */
    public function setFieldTimezoneOffset(&$field, $offset) {
        // No-op. Timezone offsets are implementation-specific and should implement
        // this method as needed.
    }
    
    /**
     * Get the timezone offset in seconds.
     *
     * @return int
     *   The offset, in seconds, for the timezone being used.
     */
    public function getTimezoneOffset() {
        $timezone = $this->setupTimezone();
        $offset = 0;
        if ($timezone) {
            $dtz = new \DateTimeZone($timezone);
            $dt = new \DateTime('now', $dtz);
            $offset = $dtz->getOffset($dt);
        }
        return $offset;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DerivativeInspectionInterface::getBaseId public function Gets the base_plugin_id of the plugin instance. 1
DerivativeInspectionInterface::getDerivativeId public function Gets the derivative_id of the plugin instance. 1
PluginBase::$definition public property Plugins' 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::$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::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides ViewsPluginInterface::buildOptionsForm 16
PluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 63
PluginBase::defineOptions protected function Information about options for all kinds of purposes will be held here. 18
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::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::init public function Initialize the plugin. Overrides ViewsPluginInterface::init 6
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 Unpacks options over our existing defaults. 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. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
PluginBase::__construct public function Constructs a PluginBase object. 19
PluginInspectionInterface::getPluginDefinition public function Gets the definition of the plugin implementation. 6
PluginInspectionInterface::getPluginId public function Gets the plugin_id of the plugin instance. 2
QueryPluginBase::$groupOperator protected property Controls how the WHERE and HAVING groups are put together.
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::addSignature public function Add a signature to the query, if such a thing is feasible. 1
QueryPluginBase::alter public function Let modules modify the query just prior to finalizing it. 1
QueryPluginBase::build public function Builds the necessary info to execute the query. 2
QueryPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginBase::calculateDependencies 1
QueryPluginBase::execute public function Executes query and fills associated view object with according values. 2
QueryPluginBase::getAggregationInfo public function Get aggregation info for group by queries. 1
QueryPluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
QueryPluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 1
QueryPluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 1
QueryPluginBase::getDateField public function Returns a Unix timestamp to database native timestamp expression. 1
QueryPluginBase::getDateFormat public function Creates cross-database date formatting. 1
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::loadEntities public function Loads all entities contained in the passed-in $results. 1
QueryPluginBase::query public function Generate a query and a countquery from all of the information supplied. Overrides PluginBase::query 1
QueryPluginBase::setFieldTimezoneOffset public function Applies a timezone offset to the given field. 2
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::setupTimezone public function Set the database to the current user timezone. 1
QueryPluginBase::setWhereGroup public function Create a new grouping for the WHERE or HAVING clause.
QueryPluginBase::submitOptionsForm public function Handle any special handling on the validate form. Overrides PluginBase::submitOptionsForm 1
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
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.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.