You are here

public function SearchApiQuery::execute in Search API 8

Executes the query and fills the associated view object with according values.

Values to set: $view->result, $view->total_rows, $view->execute_time, $view->pager['current_page'].

$view->result should contain an array of objects. The array must use a numeric index starting at 0.

Parameters

view $view: The view which is executed.

Overrides QueryPluginBase::execute

File

src/Plugin/views/query/SearchApiQuery.php, line 543

Class

SearchApiQuery
Defines a Views query class for searching on Search API indexes.

Namespace

Drupal\search_api\Plugin\views\query

Code

public function execute(ViewExecutable $view) {
  if ($this
    ->shouldAbort()) {
    if (error_displayable()) {
      foreach ($this->errors as $msg) {
        $this
          ->getMessenger()
          ->addError($msg);
      }
    }
    $view->result = [];
    $view->total_rows = 0;
    $view->execute_time = 0;
    return;
  }

  // Calculate the "skip result count" option, if it wasn't already set to
  // FALSE.
  $skip_result_count = $this->query
    ->getOption('skip result count', TRUE);
  if ($skip_result_count) {
    $skip_result_count = !$view->pager
      ->useCountQuery() && empty($view->get_total_rows);
    $this->query
      ->setOption('skip result count', $skip_result_count);
  }
  try {

    // Trigger pager preExecute().
    $view->pager
      ->preExecute($this->query);

    // Views passes sometimes NULL and sometimes the integer 0 for "All" in a
    // pager. If set to 0 items, a string "0" is passed. Therefore, we unset
    // the limit if an empty value OTHER than a string "0" was passed.
    if (!$this->limit && $this->limit !== '0') {
      $this->limit = NULL;
    }

    // Set the range. We always set this, as there might be an offset even if
    // all items are shown.
    $this->query
      ->range($this->offset, $this->limit);
    $start = microtime(TRUE);

    // Execute the search.
    $results = $this->query
      ->execute();

    // Store the results.
    if (!$skip_result_count) {
      $view->pager->total_items = $results
        ->getResultCount();
      if (!empty($view->pager->options['offset'])) {
        $view->pager->total_items -= $view->pager->options['offset'];
      }
      $view->total_rows = $view->pager->total_items;
    }
    $view->result = [];
    if ($results
      ->getResultItems()) {
      $this
        ->addResults($results, $view);
    }
    $view->execute_time = microtime(TRUE) - $start;

    // Trigger pager postExecute().
    $view->pager
      ->postExecute($view->result);
    $view->pager
      ->updatePageInfo();
  } catch (\Exception $e) {
    $this
      ->abort($e
      ->getMessage());

    // Recursion to get the same error behaviour as above.
    $this
      ->execute($view);
  }
}