You are here

public function QueryTypeRangeBase::execute in Facets 8

Adds facet info to the query using the backend native query object.

Overrides QueryTypeInterface::execute

File

src/QueryType/QueryTypeRangeBase.php, line 15

Class

QueryTypeRangeBase
A base class for query type plugins adding range.

Namespace

Drupal\facets\QueryType

Code

public function execute() {
  $query = $this->query;

  // Alter the query here.
  if (!empty($query)) {
    $options =& $query
      ->getOptions();
    $operator = $this->facet
      ->getQueryOperator();
    $field_identifier = $this->facet
      ->getFieldIdentifier();
    $exclude = $this->facet
      ->getExclude();
    $options['search_api_facets'][$field_identifier] = $this
      ->getFacetOptions();

    // Add the filter to the query if there are active values.
    $active_items = $this->facet
      ->getActiveItems();
    $filter = $query
      ->createConditionGroup($operator, [
      'facet:' . $field_identifier,
    ]);
    if (count($active_items)) {
      foreach ($active_items as $value) {
        $range = $this
          ->calculateRange($value);
        $conjunction = $exclude ? 'OR' : 'AND';
        $item_filter = $query
          ->createConditionGroup($conjunction, [
          'facet:' . $field_identifier,
        ]);
        $item_filter
          ->addCondition($this->facet
          ->getFieldIdentifier(), $range['start'], $exclude ? '<' : '>=');
        $item_filter
          ->addCondition($this->facet
          ->getFieldIdentifier(), $range['stop'], $exclude ? '>' : '<=');
        $filter
          ->addConditionGroup($item_filter);
      }
      $query
        ->addConditionGroup($filter);
    }
  }
}