You are here

public function ManyToOneHelper::addFilter in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/views/src/ManyToOneHelper.php \Drupal\views\ManyToOneHelper::addFilter()

File

core/modules/views/src/ManyToOneHelper.php, line 256

Class

ManyToOneHelper
This many to one helper object is used on both arguments and filters.

Namespace

Drupal\views

Code

public function addFilter() {
  if (empty($this->handler->value)) {
    return;
  }
  $this->handler
    ->ensureMyTable();

  // Shorten some variables:
  $field = $this
    ->getField();
  $options = $this->handler->options;
  $operator = $this->handler->operator;
  $formula = !empty($this->formula);
  $value = $this->handler->value;
  if (empty($options['group'])) {
    $options['group'] = 0;
  }

  // If $add_condition is set to FALSE, a single expression is enough. If it
  // is set to TRUE, conditions will be added.
  $add_condition = TRUE;
  if ($operator == 'not') {
    $value = NULL;
    $operator = 'IS NULL';
    $add_condition = FALSE;
  }
  elseif ($operator == 'or' && empty($options['reduce_duplicates'])) {
    if (count($value) > 1) {
      $operator = 'IN';
    }
    else {
      $value = is_array($value) ? array_pop($value) : $value;
      $operator = '=';
    }
    $add_condition = FALSE;
  }
  if (!$add_condition) {
    if ($formula) {
      $placeholder = $this
        ->placeholder();
      if ($operator == 'IN') {
        $operator = "{$operator} IN({$placeholder})";
      }
      else {
        $operator = "{$operator} {$placeholder}";
      }
      $placeholders = [
        $placeholder => $value,
      ];
      $this->handler->query
        ->addWhereExpression($options['group'], "{$field} {$operator}", $placeholders);
    }
    else {
      $placeholder = $this
        ->placeholder();
      if (count($this->handler->value) > 1) {
        $placeholder .= '[]';
        if ($operator == 'IS NULL') {
          $this->handler->query
            ->addWhereExpression(0, "{$field} {$operator}");
        }
        else {
          $this->handler->query
            ->addWhereExpression(0, "{$field} {$operator}({$placeholder})", [
            $placeholder => $value,
          ]);
        }
      }
      else {
        if ($operator == 'IS NULL') {
          $this->handler->query
            ->addWhereExpression(0, "{$field} {$operator}");
        }
        else {
          $this->handler->query
            ->addWhereExpression(0, "{$field} {$operator} {$placeholder}", [
            $placeholder => $value,
          ]);
        }
      }
    }
  }
  if ($add_condition) {
    $field = $this->handler->realField;
    $clause = $operator == 'or' ? new Condition('OR') : new Condition('AND');
    foreach ($this->handler->tableAliases as $value => $alias) {
      $clause
        ->condition("{$alias}.{$field}", $value);
    }

    // implode on either AND or OR.
    $this->handler->query
      ->addWhere($options['group'], $clause);
  }
}