You are here

class CoreViewsContextualFilter in Core Views Facets 8

Represents a facet source of the core views with contextual filters.

Plugin annotation


@FacetsFacetSource(
  id = "core_views_contextual_filter",
  deriver = "Drupal\core_views_facets\Plugin\facets\facet_source\CoreViewsContextualFilterDeriver"
)

Hierarchy

Expanded class hierarchy of CoreViewsContextualFilter

1 file declares its use of CoreViewsContextualFilter
CoreViewsUrlProcessor.php in src/Plugin/facets/url_processor/CoreViewsUrlProcessor.php

File

src/Plugin/facets/facet_source/CoreViewsContextualFilter.php, line 26

Namespace

Drupal\core_views_facets\Plugin\facets\facet_source
View source
class CoreViewsContextualFilter extends CoreViewsFacetSourceBase {

  /**
   * The filter type plugin manager.
   *
   * @var \Drupal\core_views_facets\CoreViewsFacetsContextualFilterTypeManager
   */
  protected $contextualFilterTypePluginManager;

  /**
   * Constructs a CoreViewsContextualFilter object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\facets\QueryType\QueryTypePluginManager $query_type_plugin_manager
   *   The query type plugin manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The master Request.
   * @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
   *   The route provider.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   * @param \Drupal\views\ViewExecutableFactory $executable_factory
   *   The view executable factory.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\core_views_facets\CoreViewsFacetsContextualFilterTypeManager $contextual_filter_type_plugin_manager
   *   The filter type plugin manager.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryTypePluginManager $query_type_plugin_manager, EntityTypeManagerInterface $entity_type_manager, Request $request, RouteProviderInterface $route_provider, RouteMatchInterface $route_match, ViewExecutableFactory $executable_factory, EntityFieldManagerInterface $entity_field_manager, CoreViewsFacetsContextualFilterTypeManager $contextual_filter_type_plugin_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $query_type_plugin_manager, $entity_type_manager, $request, $route_provider, $route_match, $executable_factory, $entity_field_manager);
    $this->contextualFilterTypePluginManager = $contextual_filter_type_plugin_manager;
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('plugin.manager.facets.query_type'), $container
      ->get('entity_type.manager'), $container
      ->get('request_stack')
      ->getMasterRequest(), $container
      ->get('router.route_provider'), $container
      ->get('current_route_match'), $container
      ->get('views.executable'), $container
      ->get('entity_field.manager'), $container
      ->get('plugin.manager.core_views_facets.contextual_filter_types'));
  }

  /**
   * {@inheritdoc}
   */
  public function isRenderedInCurrentRequest() {
    if (parent::isRenderedInCurrentRequest()) {
      return TRUE;
    }
    if (drupal_static('core_views_contextual_filter_ajax_rendered_status')) {
      return TRUE;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public function fillFacetsWithResults(array $facets) {
    foreach ($facets as $facet) {
      if ($facet
        ->getOnlyVisibleWhenFacetSourceIsVisible()) {

        // Ignore currently unnecessary facets.

        /** @var \Drupal\facets\FacetSource\FacetSourcePluginInterface $facet_source */
        $facet_source = $facet
          ->getFacetSource();
        if (!$facet_source
          ->isRenderedInCurrentRequest()) {
          continue;
        }
      }
      $views_arguments = $this
        ->getFields();
      reset($views_arguments);
      if (!empty($views_arguments[$facet
        ->getFieldIdentifier()])) {
        $facet_argument = $views_arguments[$facet
          ->getFieldIdentifier()];
      }
      else {
        return;
      }
      $request_arguments = [];
      $map = $this
        ->getViewsArgumentsMap();
      foreach ($map as $current_argument) {
        $request_arguments[] = $current_argument['active'] ? $current_argument['value'] : $current_argument['neutral_value'];
      }
      $this->view
        ->setArguments($request_arguments);
      $this->view
        ->build($this->pluginDefinition['view_display']);
      $facet_core_views_contextual_filter_plugin = $this
        ->loadFacetCoreViewsContextualFilterTypePlugin($facet_argument);
      if (empty($facet_core_views_contextual_filter_plugin)) {
        return;
      }
      $query = $facet_core_views_contextual_filter_plugin
        ->prepareQuery($this->view, $facet_argument, $facet);
      if (empty($query)) {
        return;
      }
      $rows = $query
        ->execute();
      $facet_results = [];
      while ($row = $rows
        ->fetchObject()) {
        $facet_results[] = $facet_core_views_contextual_filter_plugin
          ->processDatabaseRow($row, $facet_argument, $facet);
      }
      $configuration = [
        'query' => NULL,
        'facet' => $facet,
      ];
      $facet
        ->setResults($facet_results);

      // Get the Facet Specific Query Type so we can process the results
      // using the build() function of the query type.
      $query_type = $this->queryTypePluginManager
        ->createInstance($facet
        ->getQueryType(), $configuration);
      $query_type
        ->build();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $arguments = $this
      ->getFields();

    /* @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $argument */
    foreach ($arguments as $argument_id => $argument) {
      $form['field_identifier']['#options'][$argument_id] = $argument
        ->adminLabel();
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $facet_source_id = $this->facet
      ->getFacetSourceId();
    $views_arguments = $this
      ->getFields();
    $field_identifier = $form_state
      ->getValue('facet_source_configs')[$facet_source_id]['field_identifier'];
    if (empty($field_identifier) || empty($views_arguments[$field_identifier])) {
      return;
    }
    $this->facet
      ->setFieldIdentifier($field_identifier);
  }

  /**
   * Retrieve the argument definition from the current view.
   *
   * @param string|null $argument_id
   *   The string ID of a argument.
   *
   * @return array|bool
   *   An array with the definition of the argument, or FALSE when the plugin
   *   doesn't exist.
   */
  public function getViewsArgumentDefinition($argument_id = NULL) {
    if (empty($argument_id) || empty($this->view)) {
      return FALSE;
    }

    /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $argument */
    $filter = $this->view
      ->getHandler($this->pluginDefinition['view_display'], 'argument', $argument_id);
    return $filter ?: FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getFields() {
    $arguments = [];
    foreach ($this->view
      ->getHandlers('argument', $this->view->current_display) as $argument_id => $argument) {
      $arguments[$argument_id] = $this->view->display_handler
        ->getHandler('argument', $argument_id);
    }
    return $arguments;
  }

  /**
   * Load the core_views_facet contextual filter type or fall back to generic.
   *
   * @param \Drupal\views\Plugin\views\argument\ArgumentPluginBase $argument
   *   The views filter handler.
   *
   * @return \Drupal\core_views_facets\CoreViewsFacetsFilterTypeInterface
   *   The loaded filter type plugin or null.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *   If the instance cannot be created, such as if the ID is invalid.
   */
  protected function loadFacetCoreViewsContextualFilterTypePlugin(ArgumentPluginBase $argument) {
    $filter_type_definitions = $this->contextualFilterTypePluginManager
      ->getDefinitions();
    $custom_filter_id = $argument->view
      ->id() . '-' . $argument->field;

    // Allows to handle custom scenarios.
    if (!empty($filter_type_definitions[$custom_filter_id])) {

      /** @var \Drupal\core_views_facets\CoreViewsFacetsFilterTypeInterface $facet_core_views_filter_plugin */
      $facet_core_views_filter_plugin = $this->contextualFilterTypePluginManager
        ->createInstance($custom_filter_id);
    }
    elseif (!empty($filter_type_definitions[$argument->pluginId])) {

      /** @var \Drupal\core_views_facets\CoreViewsFacetsFilterTypeInterface $facet_core_views_filter_plugin */
      $facet_core_views_filter_plugin = $this->contextualFilterTypePluginManager
        ->createInstance($argument->pluginId);
    }
    else {

      /** @var \Drupal\core_views_facets\CoreViewsFacetsFilterTypeInterface $facet_core_views_filter_plugin */
      $facet_core_views_filter_plugin = $this->contextualFilterTypePluginManager
        ->createInstance('generic');
    }
    return $facet_core_views_filter_plugin;
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\facets\Exception\Exception
   */
  public function getDataDefinition($field_name) {
    $this->view
      ->build($this->pluginDefinition['view_display']);
    $definition = $this->view->argument[$field_name]->definition;
    $original_field_name = $this
      ->getOriginalFieldName($definition);
    $field_definition = $this->entityFieldManager
      ->getFieldStorageDefinitions($definition['entity_type']);
    if (isset($field_definition[$original_field_name])) {
      $property_definitions = $field_definition[$original_field_name]
        ->getPropertyDefinitions();
      $field_type = $field_definition[$original_field_name]
        ->getType();
      foreach ($property_definitions as $property_definition) {
        if ($field_type === $property_definition
          ->getDataType()) {
          return $property_definition;
        }
      }
    }
    throw new Exception("Field with name {$field_name} does not have a definition");
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CoreViewsContextualFilter::$contextualFilterTypePluginManager protected property The filter type plugin manager.
CoreViewsContextualFilter::buildConfigurationForm public function Form constructor. Overrides CoreViewsFacetSourceBase::buildConfigurationForm
CoreViewsContextualFilter::create public static function Overrides CoreViewsFacetSourceBase::create
CoreViewsContextualFilter::fillFacetsWithResults public function Overrides FacetSourcePluginInterface::fillFacetsWithResults
CoreViewsContextualFilter::getDataDefinition public function Overrides CoreViewsFacetSourceBase::getDataDefinition
CoreViewsContextualFilter::getFields public function Returns an array of fields that are defined on the facet source. Overrides FacetSourcePluginBase::getFields
CoreViewsContextualFilter::getViewsArgumentDefinition public function Retrieve the argument definition from the current view.
CoreViewsContextualFilter::isRenderedInCurrentRequest public function Returns true if the Facet source is being rendered in the current request. Overrides CoreViewsFacetSourceBase::isRenderedInCurrentRequest
CoreViewsContextualFilter::loadFacetCoreViewsContextualFilterTypePlugin protected function Load the core_views_facet contextual filter type or fall back to generic.
CoreViewsContextualFilter::submitConfigurationForm public function Form submission handler. Overrides FacetSourcePluginBase::submitConfigurationForm
CoreViewsContextualFilter::__construct public function Constructs a CoreViewsContextualFilter object. Overrides CoreViewsFacetSourceBase::__construct
CoreViewsFacetSourceBase::$entityFieldManager protected property The entity field manager.
CoreViewsFacetSourceBase::$entityTypeManager protected property The entity manager.
CoreViewsFacetSourceBase::$request protected property The master request.
CoreViewsFacetSourceBase::$routeMatch protected property The route match.
CoreViewsFacetSourceBase::$routeProvider protected property The route provider.
CoreViewsFacetSourceBase::$urlProcessor protected property The url processor name.
CoreViewsFacetSourceBase::$view protected property The current view.
CoreViewsFacetSourceBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
CoreViewsFacetSourceBase::getAjaxSettingsByFacet public function Optionally get JS settings when AJAX is enabled.
CoreViewsFacetSourceBase::getOriginalFieldName public function Get original field name.
CoreViewsFacetSourceBase::getPath public function Returns the path of the facet source, used to build the facet url. Overrides FacetSourcePluginInterface::getPath
CoreViewsFacetSourceBase::getQueryTypesForFacet public function Returns the allowed query types for a given facet for the facet source. Overrides FacetSourcePluginBase::getQueryTypesForFacet
CoreViewsFacetSourceBase::getView public function Return the current view.
CoreViewsFacetSourceBase::getViewsArgumentsMap public function Retrieves the current views arguments map and returns a detailed version.
CoreViewsFacetSourceBase::validateConfigurationForm public function Form validation handler. Overrides FacetSourcePluginBase::validateConfigurationForm
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
FacetSourcePluginBase::$facet protected property The facet we're editing for.
FacetSourcePluginBase::$keys protected property The search keys, or query text, submitted by the user.
FacetSourcePluginBase::$queryTypePluginManager protected property The plugin manager.
FacetSourcePluginBase::buildFacet public function Builds and returns an extra renderable array for this facet block plugin. Overrides FacetSourcePluginInterface::buildFacet 1
FacetSourcePluginBase::getCount public function Returns the number of results that were found for this search. Overrides FacetSourcePluginInterface::getCount 1
FacetSourcePluginBase::getSearchKeys public function Returns the search keys, or query text, submitted by the user. Overrides FacetSourcePluginInterface::getSearchKeys
FacetSourcePluginBase::setSearchKeys public function Sets the search keys, or query text, submitted by the user. Overrides FacetSourcePluginInterface::setSearchKeys
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::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
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::isConfigurable public function Determines if the plugin is configurable.
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.