You are here

public function SearchApiDisplay::fillFacetsWithResults in Facets 8

Fills the facet entities with results from the facet source.

Parameters

\Drupal\facets\FacetInterface[] $facets: The configured facets.

Overrides FacetSourcePluginInterface::fillFacetsWithResults

File

src/Plugin/facets/facet_source/SearchApiDisplay.php, line 152

Class

SearchApiDisplay
Provides a facet source based on a Search API display.

Namespace

Drupal\facets\Plugin\facets\facet_source

Code

public function fillFacetsWithResults(array $facets) {
  $search_id = $this
    ->getDisplay()
    ->getPluginId();

  // Check if the results for this search id are already populated in the
  // query helper. This is usually the case for views displays that are
  // rendered on the same page, such as views_page.
  $results = $this->searchApiQueryHelper
    ->getResults($search_id);

  // If there are no results, we can check the Search API Display plugin has
  // configuration for views. If that configuration exists, we can execute
  // that view and try to use it's results.
  $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;
  }

  // Get our facet data.
  $facet_results = $results
    ->getExtraData('search_api_facets');

  // If no data is found in the 'search_api_facets' extra data, we can stop
  // execution here.
  if ($facet_results === []) {
    return;
  }

  // Loop over each facet and execute the build method from the given
  // query type.
  foreach ($facets as $facet) {
    $configuration = [
      'query' => $results
        ->getQuery(),
      'facet' => $facet,
      'results' => isset($facet_results[$facet
        ->getFieldIdentifier()]) ? $facet_results[$facet
        ->getFieldIdentifier()] : [],
    ];

    // Get the Facet Specific Query Type so we can process the results
    // using the build() function of the query type.
    $query_type = $this->queryTypePluginManager
      ->createInstance($facet
      ->getQueryType(), $configuration);
    $query_type
      ->build();
  }
}