You are here

public function SuggestionController::autoComplete in Autocomplete Search Suggestions 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Controller/SuggestionController.php \Drupal\suggestion\Controller\SuggestionController::autoComplete()
  2. 8 src/Controller/SuggestionController.php \Drupal\suggestion\Controller\SuggestionController::autoComplete()

AJAX search autocomplete callback.

Parameters

Symfony\Component\HttpFoundation\Request $request: The Request object.

Return value

object A JSON response of search suggestions.

1 string reference to 'SuggestionController::autoComplete'
suggestion.routing.yml in ./suggestion.routing.yml
suggestion.routing.yml

File

src/Controller/SuggestionController.php, line 25

Class

SuggestionController
Suggestion menu callback.

Namespace

Drupal\suggestion\Controller

Code

public function autoComplete(Request $request) {
  $cfg = Helper::getConfig();
  $json = [];
  $txt = preg_replace([
    '/^[^a-z]+/',
    '/[^a-z]+$/',
  ], [
    '',
    ' ',
  ], strtolower($request->query
    ->get('q')));
  if (strlen($txt) < $cfg->min) {
    return new JsonResponse([]);
  }
  $count = str_word_count($txt);
  $atoms = $count < $cfg->atoms_min ? $cfg->atoms_min + 2 : $count + 2;
  $ngram = Storage::like($txt) . '%';
  $suggestions = Storage::getAutocomplete($ngram, $atoms, $cfg->limit);
  if (count($suggestions) < $cfg->limit) {
    $suggestions += Storage::getAutocomplete('%' . $ngram, $atoms, $cfg->limit - count($suggestions));
  }
  foreach ($suggestions as $suggestion) {
    $json[] = [
      'value' => $suggestion,
      'label' => $suggestion,
    ];
  }
  return new JsonResponse($json);
}