You are here

public function TestSuggester::getAutocompleteSuggestions in Search API Autocomplete 8

Retrieves autocompletion suggestions for some user input.

For example, when given the user input "teach us", with "us" being considered incomplete, \Drupal\search_api_autocomplete\SuggestionInterface objects representing the following suggestions might be returned:

[
  [
    'prefix' => t('Did you mean:'),
    'user_input' => 'reach us',
  ],
  [
    'user_input' => 'teach us',
    'suggestion_suffix' => 'ers',
  ],
  [
    'user_input' => 'teach us',
    'suggestion_suffix' => ' swimming',
  ],
];

Parameters

\Drupal\search_api\Query\QueryInterface $query: A query representing the completed user input so far.

string $incomplete_key: The start of another fulltext keyword for the search, which should be completed. Might be empty, in which case all user input up to now was considered completed. Then, additional keywords for the search could be suggested.

string $user_input: The complete user input for the fulltext search keywords so far.

Return value

\Drupal\search_api_autocomplete\Suggestion\SuggestionInterface[] An array of autocomplete suggestions.

Overrides SuggesterInterface::getAutocompleteSuggestions

File

tests/search_api_autocomplete_test/src/Plugin/search_api_autocomplete/suggester/TestSuggester.php, line 75

Class

TestSuggester
Defines a test suggester class.

Namespace

Drupal\search_api_autocomplete_test\Plugin\search_api_autocomplete\suggester

Code

public function getAutocompleteSuggestions(QueryInterface $query, $incomplete_key, $user_input) {
  $this
    ->logMethodCall(__FUNCTION__, func_get_args());
  if ($override = $this
    ->getMethodOverride(__FUNCTION__)) {
    return call_user_func($override, $this, $query, $incomplete_key, $user_input);
  }
  $suggestions = [];
  $factory = new SuggestionFactory($user_input);

  // Add some suffix-based suggestions and one URL-based suggestion.
  for ($i = 1; $i < $query
    ->getOption('limit', 10); ++$i) {
    $suggestions[] = $factory
      ->createFromSuggestionSuffix("-suggester-{$i}", $i);
  }
  $account = \Drupal::currentUser()
    ->getAccount();
  if ($uid = $account
    ->id()) {
    $url = Url::fromRoute('entity.user.canonical', [
      'user' => $uid,
    ]);
  }
  else {
    $url = Url::fromRoute('user.login');
  }
  $suggestions[] = $factory
    ->createUrlSuggestion($url, "{$user_input}-suggester-url");
  return $suggestions;
}