You are here

public function AddSearchMetaEventSubscriber::appendFacets in JSON:API Search API 8

Adds facet information into the meta of the JSON:API Search API response.

Parameters

\Drupal\jsonapi_search_api\Event\AddSearchMetaEvent $event: The event being subscribed to.

File

modules/jsonapi_search_api_facets/src/EventSubscriber/AddSearchMetaEventSubscriber.php, line 58

Class

AddSearchMetaEventSubscriber
Event subscriber to add facets into search results.

Namespace

Drupal\jsonapi_search_api_facets\EventSubscriber

Code

public function appendFacets(AddSearchMetaEvent $event) {
  $query = $event
    ->getQuery();
  if (strpos($query
    ->getSearchId(), 'jsonapi_search_api:') === 0 && $query
    ->getIndex()
    ->getServerInstance()
    ->supportsFeature('search_api_facets')) {
    $facet_source_id = strtr('jsonapi_search_api_facets:!index', [
      '!index' => $query
        ->getIndex()
        ->id(),
    ]);
    $facets = $this->facetManager
      ->getFacetsByFacetSourceId($facet_source_id);
    $meta = [];
    foreach ($facets as $facet) {

      // No need to build the facet if it does not need to be visible.
      if ($facet
        ->getOnlyVisibleWhenFacetSourceIsVisible() && (!$facet
        ->getFacetSource() || !$facet
        ->getFacetSource()
        ->isRenderedInCurrentRequest())) {
        continue;
      }

      // Let the facet_manager build the facets, it returns each facet wrapped
      // in an array for some reason. For better readability get rid of that.
      $facet_results = $this->facetManager
        ->build($facet);
      $facet_data = reset($facet_results);

      // If there are no results, the facet manager adds empty behavior render
      // array data. We need to strip that out.
      if (count($facet
        ->getResults()) === 0) {
        $facet_data = reset($facet_data);
      }
      if ($facet_data) {
        $meta[] = $facet_data;
      }
    }
    if (!empty($meta)) {
      $event
        ->setMeta('facets', $meta);
    }
  }
}