View source
<?php
namespace Drupal\facets\Plugin\facets\facet_source;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\facets\Exception\Exception;
use Drupal\facets\Exception\InvalidQueryTypeException;
use Drupal\facets\FacetInterface;
use Drupal\facets\FacetSource\FacetSourcePluginBase;
use Drupal\facets\FacetSource\SearchApiFacetSourceInterface;
use Drupal\facets\QueryType\QueryTypePluginManager;
use Drupal\search_api\Backend\BackendInterface;
use Drupal\search_api\Display\DisplayPluginManager;
use Drupal\search_api\FacetsQueryTypeMappingInterface;
use Drupal\search_api\Query\ResultSetInterface;
use Drupal\search_api\Utility\QueryHelper;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
class SearchApiDisplay extends FacetSourcePluginBase implements SearchApiFacetSourceInterface {
protected $index;
protected $displayPluginManager;
protected $searchApiQueryHelper;
protected $request;
protected $moduleHandler;
public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryTypePluginManager $query_type_plugin_manager, QueryHelper $search_results_cache, DisplayPluginManager $display_plugin_manager, Request $request, ModuleHandler $moduleHandler) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $query_type_plugin_manager);
$this->searchApiQueryHelper = $search_results_cache;
$this->displayPluginManager = $display_plugin_manager;
$this->moduleHandler = $moduleHandler;
$this->request = clone $request;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
if (!$container
->get('module_handler')
->moduleExists('search_api')) {
return new \stdClass();
}
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('plugin.manager.facets.query_type'), $container
->get('search_api.query_helper'), $container
->get('plugin.manager.search_api.display'), $container
->get('request_stack')
->getMasterRequest(), $container
->get('module_handler'));
}
public function getIndex() {
if ($this->index === NULL) {
$this->index = $this
->getDisplay()
->getIndex();
}
return $this->index;
}
public function getPath() {
if ($this
->getDisplay()
->getPath()) {
return $this
->getDisplay()
->getPath();
}
return \Drupal::service('path.current')
->getPath();
}
public function fillFacetsWithResults(array $facets) {
$search_id = $this
->getDisplay()
->getPluginId();
$results = $this->searchApiQueryHelper
->getResults($search_id);
$display_definition = $this
->getDisplay()
->getPluginDefinition();
if ($results === NULL && isset($display_definition['view_id'])) {
$view = Views::getView($display_definition['view_id']);
$view
->setDisplay($display_definition['view_display']);
$view
->execute();
$results = $this->searchApiQueryHelper
->getResults($search_id);
}
if (!$results instanceof ResultSetInterface) {
return;
}
$facet_results = $results
->getExtraData('search_api_facets');
if ($facet_results === []) {
return;
}
foreach ($facets as $facet) {
$configuration = [
'query' => $results
->getQuery(),
'facet' => $facet,
'results' => isset($facet_results[$facet
->getFieldIdentifier()]) ? $facet_results[$facet
->getFieldIdentifier()] : [],
];
$query_type = $this->queryTypePluginManager
->createInstance($facet
->getQueryType(), $configuration);
$query_type
->build();
}
}
public function isRenderedInCurrentRequest() {
return $this
->getDisplay()
->isRenderedInCurrentRequest();
}
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;
}
public function getFields() {
$indexed_fields = [];
$index = $this
->getIndex();
$fields = $index
->getFields();
$server = $index
->getServerInstance();
$backend = $server
->getBackend();
foreach ($fields as $field) {
$data_type_plugin_id = $field
->getDataTypePlugin()
->getPluginId();
$query_types = $this
->getQueryTypesForDataType($backend, $data_type_plugin_id);
if (!empty($query_types)) {
$indexed_fields[$field
->getFieldIdentifier()] = $field
->getLabel() . ' (' . $field
->getPropertyPath() . ')';
}
}
return $indexed_fields;
}
public function getQueryTypesForFacet(FacetInterface $facet) {
$field_id = $facet
->getFieldIdentifier();
$index = $this
->getIndex();
$server = $index
->getServerInstance();
$backend = $server
->getBackend();
$fields = $index
->getFields();
foreach ($fields as $field) {
if ($field
->getFieldIdentifier() == $field_id) {
return $this
->getQueryTypesForDataType($backend, $field
->getType());
}
}
throw new InvalidQueryTypeException("No available query types were found for facet {$facet->getName()}");
}
protected function getQueryTypesForDataType(BackendInterface $backend, $data_type_plugin_id) {
$query_types = [];
$query_types['string'] = 'search_api_string';
switch ($data_type_plugin_id) {
case 'date':
$query_types['date'] = 'search_api_date';
$query_types['range'] = 'search_api_range';
break;
case 'decimal':
case 'integer':
$query_types['numeric'] = 'search_api_granular';
$query_types['range'] = 'search_api_range';
break;
}
if ($backend instanceof FacetsQueryTypeMappingInterface) {
$mapping = [
$data_type_plugin_id => &$query_types,
];
$backend
->alterFacetQueryTypeMapping($mapping);
}
$backend_plugin_id = $backend
->getPluginId();
\Drupal::moduleHandler()
->alter('facets_search_api_query_type_mapping', $backend_plugin_id, $query_types);
return $query_types;
}
public function calculateDependencies() {
$display = $this
->getDisplay();
if ($display instanceof DependentPluginInterface) {
return $display
->calculateDependencies();
}
return [];
}
public function getDisplay() {
return $this->displayPluginManager
->createInstance($this->pluginDefinition['display_id']);
}
public function getViewsDisplay() {
if (!$this->moduleHandler
->moduleExists('views')) {
return NULL;
}
$search_api_display_definition = $this
->getDisplay()
->getPluginDefinition();
if (empty($search_api_display_definition['view_id'])) {
return NULL;
}
$view_id = $search_api_display_definition['view_id'];
$view_display = $search_api_display_definition['view_display'];
$view = Views::getView($view_id);
$view
->setDisplay($view_display);
return $view;
}
public function getDataDefinition($field_name) {
$field = $this
->getIndex()
->getField($field_name);
if ($field) {
return $field
->getDataDefinition();
}
throw new Exception("Field with name {$field_name} does not have a definition");
}
public function buildFacet() {
$build = parent::buildFacet();
$view = $this
->getViewsDisplay();
if ($view === NULL) {
return $build;
}
if ($view->display_handler
->ajaxEnabled()) {
$js_settings = [
'view_id' => $view
->id(),
'current_display_id' => $view->current_display,
'view_base_path' => ltrim($view
->getPath(), '/'),
'ajax_path' => Url::fromRoute('views.ajax')
->toString(),
];
$build['#attached']['library'][] = 'facets/drupal.facets.views-ajax';
$build['#attached']['drupalSettings']['facets_views_ajax'] = [
$this->facet
->id() => $js_settings,
];
$build['#use_ajax'] = TRUE;
}
return $build;
}
public function getCount() {
$search_id = $this
->getDisplay()
->getPluginId();
if ($search_id && !empty($search_id)) {
if ($this->searchApiQueryHelper
->getResults($search_id) !== NULL) {
return $this->searchApiQueryHelper
->getResults($search_id)
->getResultCount();
}
}
}
}