You are here

public function TestBackend::search in Search API 8

Executes a search on this server.

Parameters

\Drupal\search_api\Query\QueryInterface $query: The query to execute.

Throws

\Drupal\search_api\SearchApiException Thrown if an error prevented the search from completing.

Overrides BackendSpecificInterface::search

File

tests/search_api_test/src/Plugin/search_api/backend/TestBackend.php, line 233

Class

TestBackend
Provides a dummy backend for testing purposes.

Namespace

Drupal\search_api_test\Plugin\search_api\backend

Code

public function search(QueryInterface $query) {
  if ($override = $this
    ->getMethodOverride(__FUNCTION__)) {
    call_user_func($override, $this, $query);
    return;
  }
  $this
    ->checkError(__FUNCTION__);
  $results = $query
    ->getResults();
  $result_items = [];
  $datasources = $query
    ->getIndex()
    ->getDatasources();

  /** @var \Drupal\search_api\Datasource\DatasourceInterface $datasource */
  $datasource = reset($datasources);
  $datasource_id = $datasource
    ->getPluginId();
  $fields_helper = \Drupal::getContainer()
    ->get('search_api.fields_helper');
  if ($query
    ->getKeys() && $query
    ->getKeys()[0] == 'test') {
    $item_id = Utility::createCombinedId($datasource_id, '1');
    $item = $fields_helper
      ->createItem($query
      ->getIndex(), $item_id, $datasource);
    $item
      ->setScore(2);
    $item
      ->setExcerpt('test');
    $result_items[$item_id] = $item;
  }
  elseif ($query
    ->getOption('search_api_mlt')) {
    $item_id = Utility::createCombinedId($datasource_id, '2');
    $item = $fields_helper
      ->createItem($query
      ->getIndex(), $item_id, $datasource);
    $item
      ->setScore(2);
    $item
      ->setExcerpt('test test');
    $result_items[$item_id] = $item;
  }
  else {
    $item_id = Utility::createCombinedId($datasource_id, '1');
    $item = $fields_helper
      ->createItem($query
      ->getIndex(), $item_id, $datasource);
    $item
      ->setScore(1);
    $result_items[$item_id] = $item;
    $item_id = Utility::createCombinedId($datasource_id, '2');
    $item = $fields_helper
      ->createItem($query
      ->getIndex(), $item_id, $datasource);
    $item
      ->setScore(1);
    $result_items[$item_id] = $item;
  }
  $results
    ->setResultItems($result_items);
  $results
    ->setResultCount(count($result_items));
}