You are here

class ActivityPlugin in Activity 8

Activity views query plugin which display all activities.

Plugin annotation


@ViewsQuery(
  id = "activity",
  title = @Translation("All activities"),
  help = @Translation("Display all actions.")
)

Hierarchy

Expanded class hierarchy of ActivityPlugin

2 string references to 'ActivityPlugin'
ActivityPlugin::calculateDependencies in src/Plugin/views/query/ActivityPlugin.php
Calculates dependencies for the configured plugin.
views.view.all_activities.yml in config/optional/views.view.all_activities.yml
config/optional/views.view.all_activities.yml

File

src/Plugin/views/query/ActivityPlugin.php, line 22

Namespace

Drupal\activity\Plugin\views\query
View source
class ActivityPlugin extends QueryPluginBase {

  /**
   * Array of conditions.
   *
   * @var array
   */
  protected $conditions = [];

  /**
   * The fields to SELECT.
   *
   * @var array
   */
  protected $fields = [];

  /**
   * An array of stdClasses.
   *
   * @var array
   */
  protected $allItems = [];

  /**
   * An array for order the query.
   *
   * @var array
   */
  protected $orderBy = [];

  /**
   * A condition array for query.
   *
   * @var array
   */
  protected $where = [];

  /**
   * Store all actions.
   *
   * @var \Drupal\Core\Database\Query\SelectInterface
   */
  protected $activities;

  /**
   * Object used to extract data from activity tables.
   *
   * @var \Drupal\activity\QueryActivity
   */
  protected $activityQuery;

  /**
   * Activity constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\activity\QueryActivity $activityQuery
   *   Query Activity service.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, QueryActivity $activityQuery) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->activityQuery = $activityQuery;
    $this->activities = $this->activityQuery
      ->getActivities();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('query_activity'));
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['accept_lang'] = [
      'default' => NULL,
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function addWhere($group, $field, $value = NULL, $operator = NULL) {
    if (empty($group)) {
      $group = 0;
    }

    // Check for a group.
    if (!isset($this->where[$group])) {
      $this
        ->setWhereGroup('AND', $group);
    }
    if ($this->activities instanceof Select) {
      $this->activities
        ->condition($field, $value, $operator);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function addWhereExpression($group, $snippet, $args = []) {

    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
    // the default group.
    if (empty($group)) {
      $group = 0;
    }

    // Check for a group.
    if (!isset($this->where[$group])) {
      $this
        ->setWhereGroup('AND', $group);
    }
    $this->where[$group]['conditions'][] = [
      'field' => $snippet,
      'value' => $args,
      'operator' => 'formula',
    ];
    if ($this->activities instanceof Select) {
      $this->activities
        ->where($snippet, []);
    }
  }

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

  /**
   * {@inheritdoc}
   */
  public function addField($table, $field, $alias = '', $params = []) {
    $this->fields[$field] = $field;
    return $field;
  }

  /**
   * {@inheritdoc}
   */
  public function addOrderBy($table, $field, $order = 'ASC', $alias = '', $params = []) {

    // Only ensure the table if it's not the special random key.
    // @todo: Maybe it would make sense to just add an addOrderByRand or something similar.
    if ($table && $table != 'rand') {
      $this
        ->ensureTable($table);
    }

    // Only fill out this aliasing if there is a table;
    // otherwise we assume it is a formula.
    if (!$alias && $table) {
      $as = $table . '_' . $field;
    }
    else {
      $as = $alias;
    }
    if ($field) {
      $as = $this
        ->addField($table, $field, $as, $params);
    }
    if ($this->activities instanceof Select) {
      $this->activities
        ->orderBy($as, strtoupper($order));
    }
  }

  /**
   * Sets the allItems property.
   *
   * @param array $allItems
   *   An array of stdClasses.
   */
  public function setAllItems(array $allItems) {
    $this->allItems = $allItems;
  }

  /**
   * Implements Drupal\views\Plugin\views\query\QueryPluginBase::build().
   *
   * @param \Drupal\views\ViewExecutable $view
   *   The view.
   */
  public function build(ViewExecutable $view) {
    $this->view = $view;
    $view
      ->initPager();

    // Let the pager modify the query to add limits.
    $view->pager
      ->query();

    // Clear cache in order to obtain the right result.
    Cache::invalidateTags([
      'config:views.view.' . $view
        ->id(),
    ]);
    $view->build_info['query'] = $this->activities;
    $view->build_info['count_query'] = $this->activityQuery
      ->countMessages();
  }

  /**
   * {@inheritdoc}
   */
  public function execute(ViewExecutable $view) {
    parent::execute($view);
    $count_query = $view->build_info['count_query'];
    $count_query
      ->preExecute();

    // Build the count query.
    $count_query = $count_query
      ->countQuery();
    try {
      if ($view->pager
        ->useCountQuery() || !empty($view->get_total_rows)) {
        $view->pager
          ->executeCountQuery($count_query);
      }
      $view->pager
        ->preExecute($query);
      if ($this->activities instanceof Select) {
        if (!empty($this->limit) || !empty($this->offset)) {

          // We can't have an offset without a limit,
          // so provide a very large limit instead.
          $limit = intval(!empty($this->limit) ? $this->limit : 999999);
          $offset = intval(!empty($this->offset) ? $this->offset : 0);
          $this->activities
            ->range($offset, $limit);
        }
        $result = $this->activities
          ->execute();
        $result
          ->setFetchMode(\PDO::FETCH_CLASS, 'Drupal\\views\\ResultRow');

        // Setup the result row objects.
        $view->result = iterator_to_array($result);
        array_walk($view->result, function (ResultRow $row, $index) {
          $row->index = $index;
        });
        $view->pager
          ->postExecute($view->result);
        $view->pager
          ->updatePageInfo();
        $view->total_rows = $view->pager
          ->getTotalItems();
        $this
          ->loadEntities($view->result);
      }
    } catch (DatabaseExceptionWrapper $e) {
      $view->result = [];
      if (!empty($view->live_preview)) {
        drupal_set_message($e
          ->getMessage(), 'activity error view.');
      }
      else {
        throw new DatabaseExceptionWrapper("Exception in {$view->storage->label()}[{$view->storage->id()}]: {$e->getMessage()}");
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function match($element, $condition) {
    $value = $element[$condition['field']];
    switch ($condition['operator']) {
      case '=':
        return $value == $condition['value'];
      case 'IN':
        return in_array($value, $condition['value']);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return parent::calculateDependencies() + [
      'content' => [
        'ActivityPlugin',
      ],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ActivityPlugin::$activities protected property Store all actions.
ActivityPlugin::$activityQuery protected property Object used to extract data from activity tables.
ActivityPlugin::$allItems protected property An array of stdClasses.
ActivityPlugin::$conditions protected property Array of conditions.
ActivityPlugin::$fields protected property The fields to SELECT.
ActivityPlugin::$orderBy protected property An array for order the query.
ActivityPlugin::$where protected property A condition array for query.
ActivityPlugin::addField public function
ActivityPlugin::addOrderBy public function
ActivityPlugin::addWhere public function
ActivityPlugin::addWhereExpression public function
ActivityPlugin::build public function Implements Drupal\views\Plugin\views\query\QueryPluginBase::build(). Overrides QueryPluginBase::build
ActivityPlugin::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides QueryPluginBase::calculateDependencies
ActivityPlugin::create public static function Creates an instance of the plugin. Overrides PluginBase::create
ActivityPlugin::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides PluginBase::defineOptions
ActivityPlugin::ensureTable public function
ActivityPlugin::execute public function Executes the query and fills the associated view object with according values. Overrides QueryPluginBase::execute
ActivityPlugin::match public function
ActivityPlugin::setAllItems public function Sets the allItems property.
ActivityPlugin::__construct public function Activity constructor. Overrides PluginBase::__construct
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 protected property The messenger. 29
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::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides ViewsPluginInterface::buildOptionsForm 16
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::init public function Initialize the plugin. Overrides ViewsPluginInterface::init 8
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::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::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. . 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]; 1
QueryPluginBase::query public function Generate a query and a countquery from all of the information supplied to the object. 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
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.