You are here

protected function Highlight::addExcerpts in Search API 8

Adds excerpts to all results, if possible.

Parameters

\Drupal\search_api\Item\ItemInterface[] $results: The result items to which excerpts should be added.

string[] $fulltext_fields: The fulltext fields from which the excerpt should be created.

array $keys: The search keys to use for highlighting.

1 call to Highlight::addExcerpts()
Highlight::postprocessSearchResults in src/Plugin/search_api/processor/Highlight.php
Postprocess search results before they are returned by the query.

File

src/Plugin/search_api/processor/Highlight.php, line 274

Class

Highlight
Adds a highlighted excerpt to results and highlights returned fields.

Namespace

Drupal\search_api\Plugin\search_api\processor

Code

protected function addExcerpts(array $results, array $fulltext_fields, array $keys) {
  $items = $this
    ->getFulltextFields($results, $fulltext_fields);
  foreach ($items as $item_id => $item) {
    if (!$item) {
      continue;
    }

    // We call array_merge() using call_user_func_array() to prevent having to
    // use it in a loop because it is a resource greedy construction.
    // @see https://github.com/kalessil/phpinspectionsea/blob/master/docs/performance.md#slow-array-function-used-in-loop
    $text = call_user_func_array('array_merge', array_values($item));
    $item_keys = $keys;

    // If the backend already did highlighting and told us the exact keys it
    // found in the item's text values, we can use those for our own
    // highlighting. This will help us take stemming, transliteration, etc.
    // into account properly.
    $highlighted_keys = $results[$item_id]
      ->getExtraData('highlighted_keys');
    if ($highlighted_keys) {
      $item_keys = array_unique(array_merge($keys, $highlighted_keys));
    }

    // @todo This is pretty poor handling for the borders between different
    //   values/fields. Better would be to pass an array and have proper
    //   handling of this in createExcerpt(), ensuring that no snippet goes
    //   across multiple values/fields.
    $results[$item_id]
      ->setExcerpt($this
      ->createExcerpt(implode($this
      ->getEllipses()[1], $text), $item_keys));
  }
}