You are here

class CoreViewsExposedFilter in Core Views Facets 8

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

Plugin annotation


@FacetsFacetSource(
  id = "core_views_exposed_filter",
  deriver = "Drupal\core_views_facets\Plugin\facets\facet_source\CoreViewsExposedFilterDeriver"
)

Hierarchy

Expanded class hierarchy of CoreViewsExposedFilter

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

File

src/Plugin/facets/facet_source/CoreViewsExposedFilter.php, line 27

Namespace

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

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

  /**
   * 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\CoreViewsFacetsExposedFilterTypeManager $exposed_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, CoreViewsFacetsExposedFilterTypeManager $exposed_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->exposedFilterTypePluginManager = $exposed_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.exposed_filter_types'));
  }

  /**
   * {@inheritdoc}
   */
  public function isRenderedInCurrentRequest() {
    if (parent::isRenderedInCurrentRequest()) {
      return TRUE;
    }
    if (drupal_static('core_views_exposed_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;
        }
      }
      $request_arguments = [];
      $map = $this
        ->getViewsArgumentsMap();
      foreach ($map as $current_argument) {
        if ($current_argument['active']) {
          $request_arguments[] = $current_argument['value'];
        }
        else {
          break;
        }
      }
      $this->view
        ->setArguments($request_arguments);
      $filters = $this
        ->getFields();
      if (empty($filters[$facet
        ->getFieldIdentifier()])) {
        return;
      }
      $filter = $filters[$facet
        ->getFieldIdentifier()];
      $this->view
        ->build($this->pluginDefinition['view_display']);
      $facet_core_views_exposed_filter_plugin = $this
        ->loadFacetCoreViewsExposedFilterTypePlugin($filter);
      if (empty($facet_core_views_exposed_filter_plugin)) {
        return;
      }
      $query = $facet_core_views_exposed_filter_plugin
        ->prepareQuery($this->view, $filter, $facet);
      if (empty($query)) {
        return;
      }
      try {
        $rows = $query
          ->execute();
      } catch (DatabaseExceptionWrapper $e) {
        continue;
      }
      $facet_results = [];
      while ($row = $rows
        ->fetchObject()) {
        $facet_results[] = $facet_core_views_exposed_filter_plugin
          ->processDatabaseRow($row, $filter, $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);
    $filters = $this
      ->getFields();

    /* @var \Drupal\views\Plugin\views\filter\FilterPluginBase $filter */
    foreach ($filters as $filter_id => $filter) {
      if (!$filter
        ->isExposed()) {
        continue;
      }
      $form['field_identifier']['#options'][$filter_id] = $filter
        ->adminLabel();
    }
    return $form;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function getFields() {
    $filters = [];
    foreach ($this->view
      ->getHandlers('filter', $this->view->current_display) as $filter_id => $filter) {
      if (empty($filter['exposed']) || $filter['exposed'] != TRUE) {
        continue;
      }
      $filters[$filter_id] = $this->view->display_handler
        ->getHandler('filter', $filter_id);
    }
    return $filters;
  }

  /**
   * Load the core_views_facet filter type or fall back to generic.
   *
   * @param \Drupal\views\Plugin\views\filter\FilterPluginBase $filter
   *   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 loadFacetCoreViewsExposedFilterTypePlugin(FilterPluginBase $filter) {
    $filter_type_definitions = $this->exposedFilterTypePluginManager
      ->getDefinitions();
    $custom_filter_id = $filter->view
      ->id() . '-' . $filter->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->exposedFilterTypePluginManager
        ->createInstance($custom_filter_id);
    }
    elseif (!empty($filter_type_definitions[$filter->pluginId])) {

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

      /** @var \Drupal\core_views_facets\CoreViewsFacetsFilterTypeInterface $facet_core_views_filter_plugin */
      $facet_core_views_filter_plugin = $this->exposedFilterTypePluginManager
        ->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->filter[$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
CoreViewsExposedFilter::$exposedFilterTypePluginManager protected property The filter type plugin manager.
CoreViewsExposedFilter::buildConfigurationForm public function Form constructor. Overrides CoreViewsFacetSourceBase::buildConfigurationForm
CoreViewsExposedFilter::create public static function Overrides CoreViewsFacetSourceBase::create
CoreViewsExposedFilter::fillFacetsWithResults public function Overrides FacetSourcePluginInterface::fillFacetsWithResults
CoreViewsExposedFilter::getDataDefinition public function Overrides CoreViewsFacetSourceBase::getDataDefinition
CoreViewsExposedFilter::getFields public function Returns an array of fields that are defined on the facet source. Overrides FacetSourcePluginBase::getFields
CoreViewsExposedFilter::getViewsFilterDefinition public function Retrieve the filter definition from the current view.
CoreViewsExposedFilter::isRenderedInCurrentRequest public function Returns true if the Facet source is being rendered in the current request. Overrides CoreViewsFacetSourceBase::isRenderedInCurrentRequest
CoreViewsExposedFilter::loadFacetCoreViewsExposedFilterTypePlugin protected function Load the core_views_facet filter type or fall back to generic.
CoreViewsExposedFilter::submitConfigurationForm public function Form submission handler. Overrides FacetSourcePluginBase::submitConfigurationForm
CoreViewsExposedFilter::__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.