Advertisement
Guest User

Untitled

a guest
Sep 8th, 2016
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.75 KB | None | 0 0
  1.  
  2. use Drupal\search_api\Query\QueryInterface;
  3. use Drupal\search_api\SearchApiException;
  4. use Drupal\search_api_autocomplete\Entity\SearchApiAutocompleteSearch;
  5. use Drupal\search_api_autocomplete\Suggestion;
  6.  
  7. trait SolrBackendImprovedTrait {
  8.  
  9.   public function supportsFeature($feature) {
  10.     return $feature === 'search_api_autocomplete' ? $feature : parent::supportsFeature($feature); // TODO: Change the autogenerated stub
  11.   }
  12.  
  13.   public function getAutocompleteSuggestions(QueryInterface $query, SearchApiAutocompleteSearch $search, $incomplete_key, $user_input) {
  14.     $suggestions = [];
  15.     try {
  16.       $query->keys($incomplete_key);
  17.       $query->setOption('search_api_spellcheck', 'true');
  18.       $query->setOption('search_api_spellcheck.count', 1);
  19.       $this->search($query);
  20.       $response = $query->getResults();
  21.       if (!empty($response->getAllExtraData()['search_api_solr_response']['spellcheck']['suggestions'])) {
  22.         $variants = $response->getAllExtraData()['search_api_solr_response']['spellcheck']['suggestions'];
  23.         $replace = array();
  24.         while ($variants) {
  25.           $word = array_shift($variants);
  26.           $replace[$word] = array_shift($variants)['suggestion'][0];
  27.         }
  28.         $corrected = str_ireplace(array_keys($replace), array_values($replace), $user_input);
  29.         if ($corrected != $user_input) {
  30.           $suggestion = new Suggestion(null, '',  $this->t('Did you mean:'), '', $corrected);
  31.           array_unshift($suggestions, $suggestion);
  32.         }
  33.       }
  34.     } catch (SearchApiException $e) {
  35.       watchdog_exception('search_api_solr', $e, "%type during autocomplete Solr query: !message in %function (line %line of %file).", array(), WATCHDOG_WARNING);
  36.     }
  37.     return $suggestions;
  38.   }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement