You are here

public function SearchApiViewsQuery::build in Search API 7

Builds the necessary info to execute the query.

Overrides views_plugin_query::build

File

contrib/search_api_views/includes/query.inc, line 263
Contains SearchApiViewsQuery.

Class

SearchApiViewsQuery
Views query class using a Search API index as the data source.

Code

public function build(&$view) {
  if (!empty($this->errors)) {
    return;
  }
  $this->view = $view;

  // Setup the nested filter structure for this query.
  if (!empty($this->where)) {

    // If the different groups are combined with the OR operator, we have to
    // add a new OR filter to the query to which the filters for the groups
    // will be added.
    if ($this->group_operator === 'OR') {
      $base = $this->query
        ->createFilter('OR');
      $this->query
        ->filter($base);
    }
    else {
      $base = $this->query;
    }

    // Add a nested filter for each filter group, with its set conjunction.
    foreach ($this->where as $group_id => $group) {
      if (!empty($group['conditions']) || !empty($group['filters'])) {
        $group += array(
          'type' => 'AND',
        );

        // For filters without a group, we want to always add them directly to
        // the query.
        $filter = $group_id === '' ? $this->query : $this->query
          ->createFilter($group['type']);
        if (!empty($group['conditions'])) {
          foreach ($group['conditions'] as $condition) {
            list($field, $value, $operator) = $condition;
            $filter
              ->condition($field, $value, $operator);
          }
        }
        if (!empty($group['filters'])) {
          foreach ($group['filters'] as $nested_filter) {
            $filter
              ->filter($nested_filter);
          }
        }

        // If no group was given, the filters were already set on the query.
        if ($group_id !== '') {
          $base
            ->filter($filter);
        }
      }
    }
  }

  // Initialize the pager and let it modify the query to add limits.
  $view
    ->init_pager();
  $this->pager
    ->query();

  // Set the search ID, if it was not already set.
  if ($this->query
    ->getOption('search id') == get_class($this->query)) {
    $this->query
      ->setOption('search id', 'search_api_views:' . $view->name . ':' . $view->current_display);
  }

  // Add the "search_api_bypass_access" option to the query, if desired.
  if (!empty($this->options['search_api_bypass_access'])) {
    $this->query
      ->setOption('search_api_bypass_access', TRUE);
  }

  // Store the Views base path.
  $this->query
    ->setOption('search_api_base_path', $this->view
    ->get_path());

  // Save query information for Views UI.
  $view->build_info['query'] = (string) $this->query;
}