You are here

public function SearchApiQueryPreExecute::includeFacetsInQuery in JSON:API Search API 8

Alter the Search API query to include Facets if enabled.

Parameters

\Drupal\search_api\Event\QueryPreExecuteEvent $event: The event being emitted by Search API.

File

modules/jsonapi_search_api_facets/src/EventSubscriber/SearchApiQueryPreExecute.php, line 47

Class

SearchApiQueryPreExecute
Adds Facets support to a Search API Query.

Namespace

Drupal\jsonapi_search_api_facets\EventSubscriber

Code

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;
      }
    }

    // When using the OR operator for facets a filter is created to
    // support tagging and excluding filters. The base JSON:API search will
    // add the initial filter from the URL parameters which will stomp over
    // the one that is added via facets.
    // Only way to alter these conditions is modifying by reference.
    // @see: https://www.drupal.org/project/search_api/issues/2910522#comment-12270738.
    $conditions = $query
      ->getConditionGroup();
    $this
      ->removeAliasConditions($conditions, $aliased_facets);
    $this
      ->tagConditionsWithFacetTags($conditions, $facet_tags);
  }
}