You are here

abstract class SearchApiBaseFacetSource in Facets 8

A base class for Search API facet sources.

Hierarchy

Expanded class hierarchy of SearchApiBaseFacetSource

File

src/Plugin/facets/facet_source/SearchApiBaseFacetSource.php, line 19

Namespace

Drupal\facets\Plugin\facets\facet_source
View source
abstract class SearchApiBaseFacetSource extends FacetSourcePluginBase implements SearchApiFacetSourceInterface {

  /**
   * The search index.
   *
   * @var \Drupal\search_api\IndexInterface
   *
   * @deprecated in facets:8.x-1.5 and is removed from facets:8.x-2.0. Classes
   *   extending SearchApiBaseFacetSource should implement ::getIndex() instead.
   */
  protected $index;

  /**
   * The search result cache.
   *
   * @var \Drupal\search_api\Utility\QueryHelper
   */
  protected $searchApiQueryHelper;

  /**
   * Constructs a SearchApiBaseFacetSource 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\search_api\Utility\QueryHelper $search_results_cache
   *   The query type plugin manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryTypePluginManager $query_type_plugin_manager, QueryHelper $search_results_cache) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $query_type_plugin_manager);

    // Since defaultConfiguration() depends on the plugin definition, we need to
    // override the constructor and set the definition property before calling
    // that method.
    $this->pluginDefinition = $plugin_definition;
    $this->pluginId = $plugin_id;
    $this->configuration = $configuration;
    $this->searchApiQueryHelper = $search_results_cache;
  }

  /**
   * {@inheritdoc}
   */
  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('search_api.query_helper'));
  }

  /**
   * {@inheritdoc}
   */
  public function getIndex() {
    @trigger_error('Relying on $this->index is deprecated in facets:8.x-1.5. It will be removed from facets:8.x-2.0. Instead, all subclasses should implement ::getIndex() themselves, and the blanket implementation will be removed from SearchApiBaseFacetSource. See https://www.drupal.org/node/3154173', E_USER_DEPRECATED);
    return $this->index;
  }

  /**
   * {@inheritdoc}
   */
  public function getDisplay() {
    return $this
      ->getPluginDefinition()['display_id'];
  }

  /**
   * {@inheritdoc}
   */
  public function getViewsDisplay() {
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['field_identifier'] = [
      '#type' => 'select',
      '#options' => $this
        ->getFields(),
      '#title' => $this
        ->t('Field'),
      '#description' => $this
        ->t('The field from the selected facet source which contains the data to build a facet for.<br> The field types supported are <strong>boolean</strong>, <strong>date</strong>, <strong>decimal</strong>, <strong>integer</strong> and <strong>string</strong>.'),
      '#required' => TRUE,
      '#default_value' => $this->facet
        ->getFieldIdentifier(),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getFields() {
    $indexed_fields = [];
    $fields = $this
      ->getIndex()
      ->getFields();

    // Get the Search API Server.
    $server = $this
      ->getIndex()
      ->getServerInstance();

    // Get the Search API Backend.
    $backend = $server
      ->getBackend();
    foreach ($fields as $field) {
      $query_types = $this
        ->getQueryTypesForDataType($backend, $field
        ->getDataTypePlugin()
        ->getPluginId());
      if (!empty($query_types)) {
        $indexed_fields[$field
          ->getFieldIdentifier()] = $field
          ->getLabel() . ' (' . $field
          ->getPropertyPath() . ')';
      }
    }
    return $indexed_fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getQueryTypesForFacet(FacetInterface $facet) {

    // Get our Facets Field Identifier, which is equal to the Search API Field
    // identifier.
    $field_id = $facet
      ->getFieldIdentifier();

    // Get the Search API Server.
    $server = $this
      ->getIndex()
      ->getServerInstance();

    // Get the Search API Backend.
    $backend = $server
      ->getBackend();
    $fields = $this
      ->getIndex()
      ->getFields();
    if (isset($fields[$field_id])) {
      return $this
        ->getQueryTypesForDataType($backend, $fields[$field_id]
        ->getType());
    }
    throw new InvalidQueryTypeException("No available query types were found for facet {$facet->getName()}");
  }

  /**
   * Retrieves the query types for a specified data type.
   *
   * Backend plugins can use this method to override the default query types
   * provided by the Search API with backend-specific ones that better use
   * features of that backend.
   *
   * @param \Drupal\search_api\Backend\BackendInterface $backend
   *   The backend that we want to get the query types for.
   * @param string $data_type_plugin_id
   *   The identifier of the data type.
   *
   * @return string[]
   *   An associative array with the plugin IDs of allowed query types, keyed by
   *   the generic name of the query_type.
   *
   * @see hook_facets_search_api_query_type_mapping_alter()
   */
  public function getQueryTypesForDataType(BackendInterface $backend, $data_type_plugin_id) {
    $query_types = [];
    $query_types['string'] = 'search_api_string';

    // Add additional query types for specific data types.
    switch ($data_type_plugin_id) {
      case 'date':
        $query_types['date'] = 'search_api_date';
        break;
      case 'decimal':
      case 'integer':
        $query_types['numeric'] = 'search_api_granular';
        $query_types['range'] = 'search_api_range';
        break;
    }

    // Find out if the backend implemented the Interface to retrieve specific
    // query types for the supported data_types.
    if ($backend instanceof FacetsQueryTypeMappingInterface) {

      // If the input arrays have the same string keys, then the later value
      // for that key will overwrite the previous one. If, however, the arrays
      // contain numeric keys, the later value will not overwrite the original
      // value, but will be appended.
      $query_types = array_merge($query_types, $backend
        ->getQueryTypesForDataType($data_type_plugin_id));
    }

    // Add it to a variable so we can pass it by reference. Alter hook complains
    // due to the property of the backend object is not passable by reference.
    $backend_plugin_id = $backend
      ->getPluginId();

    // Let modules alter this mapping.
    \Drupal::moduleHandler()
      ->alter('facets_search_api_query_type_mapping', $backend_plugin_id, $query_types);
    return $query_types;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
DependentPluginInterface::calculateDependencies public function Calculates dependencies for the configured plugin. 19
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::isRenderedInCurrentRequest public function Returns true if the Facet source is being rendered in the current request. Overrides FacetSourcePluginInterface::isRenderedInCurrentRequest 1
FacetSourcePluginBase::setSearchKeys public function Sets the search keys, or query text, submitted by the user. Overrides FacetSourcePluginInterface::setSearchKeys
FacetSourcePluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
FacetSourcePluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
FacetSourcePluginInterface::fillFacetsWithResults public function Fills the facet entities with results from the facet source. 1
FacetSourcePluginInterface::getDataDefinition public function Returns a single field's data definition from the facet source. 1
FacetSourcePluginInterface::getPath public function Returns the path of the facet source, used to build the facet url. 1
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.
SearchApiBaseFacetSource::$index Deprecated protected property The search index.
SearchApiBaseFacetSource::$searchApiQueryHelper protected property The search result cache.
SearchApiBaseFacetSource::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
SearchApiBaseFacetSource::create public static function Creates an instance of the plugin. Overrides FacetSourcePluginBase::create
SearchApiBaseFacetSource::getDisplay public function Retrieves the Search API display plugin associated with this facet source. Overrides SearchApiFacetSourceInterface::getDisplay
SearchApiBaseFacetSource::getFields public function Returns an array of fields that are defined on the facet source. Overrides FacetSourcePluginBase::getFields
SearchApiBaseFacetSource::getIndex public function Returns the search_api index. Overrides SearchApiFacetSourceInterface::getIndex
SearchApiBaseFacetSource::getQueryTypesForDataType public function Retrieves the query types for a specified data type.
SearchApiBaseFacetSource::getQueryTypesForFacet public function Returns the allowed query types for a given facet for the facet source. Overrides FacetSourcePluginBase::getQueryTypesForFacet
SearchApiBaseFacetSource::getViewsDisplay public function Retrieves the Views entity with the correct display set. Overrides SearchApiFacetSourceInterface::getViewsDisplay
SearchApiBaseFacetSource::__construct public function Constructs a SearchApiBaseFacetSource object. Overrides FacetSourcePluginBase::__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.