SearchApiQueryPreExecute.php in JSON:API Search API 8
File
modules/jsonapi_search_api_facets/src/EventSubscriber/SearchApiQueryPreExecute.php
View source
<?php
namespace Drupal\jsonapi_search_api_facets\EventSubscriber;
use Drupal\facets\FacetManager\DefaultFacetManager;
use Drupal\search_api\Event\QueryPreExecuteEvent;
use Drupal\search_api\Event\SearchApiEvents;
use Drupal\search_api\Query\ConditionGroupInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SearchApiQueryPreExecute implements EventSubscriberInterface {
protected $facetManager;
public function __construct(DefaultFacetManager $facet_manager) {
$this->facetManager = $facet_manager;
}
public static function getSubscribedEvents() {
$events[SearchApiEvents::QUERY_PRE_EXECUTE][] = [
'includeFacetsInQuery',
];
return $events;
}
public function includeFacetsInQuery(QueryPreExecuteEvent $event) {
$query = $event
->getQuery();
$search_id = $query
->getSearchId();
if (strpos($search_id, 'jsonapi_search_api:') === 0 && $query
->getIndex()
->getServerInstance()
->supportsFeature('search_api_facets')) {
$facet_source_id = strtr('jsonapi_search_api_facets:!index', [
'!index' => $query
->getIndex()
->id(),
]);
$this->facetManager
->alterQuery($query, $facet_source_id);
$facets = $this->facetManager
->getFacetsByFacetSourceId($facet_source_id);
$facet_tags = [];
$aliased_facets = [];
foreach ($facets as $facet) {
if ($facet
->getUrlAlias() !== $facet
->getFieldIdentifier()) {
$aliased_facets[] = $facet
->getUrlAlias();
}
if ($facet
->getQueryOperator() === 'or') {
$facet_field = $facet
->getFieldIdentifier();
$facet_tag = strtr('facet:!field', [
'!field' => $facet_field,
]);
$facet_tags[$facet_field] = $facet_tag;
}
}
$conditions = $query
->getConditionGroup();
$this
->removeAliasConditions($conditions, $aliased_facets);
$this
->tagConditionsWithFacetTags($conditions, $facet_tags);
}
}
protected function removeAliasConditions(ConditionGroupInterface $condition_group, array $aliases) {
$conditions =& $condition_group
->getConditions();
foreach ($conditions as $key => $condition) {
if ($condition instanceof ConditionGroupInterface) {
$this
->removeAliasConditions($condition, $aliases);
}
else {
if (in_array($condition
->getField(), $aliases, TRUE)) {
unset($conditions[$key]);
}
}
}
}
protected function tagConditionsWithFacetTags($condition_or_group, array $facet_tags) {
if ($condition_or_group instanceof ConditionGroupInterface) {
foreach ($condition_or_group
->getConditions() as $condition) {
$tags_to_add = $this
->tagConditionsWithFacetTags($condition, $facet_tags);
if ($tags_to_add) {
$tags =& $condition_or_group
->getTags();
$tags[$tags_to_add] = $tags_to_add;
}
}
}
else {
$field = $condition_or_group
->getField();
if (isset($facet_tags[$field])) {
return $facet_tags[$field];
}
}
}
}