You are here

public function IndexNameDepth::query in Views Taxonomy Term Name Depth 8

Same name and namespace in other branches
  1. 8.6 src/Plugin/views/argument/IndexNameDepth.php \Drupal\views_taxonomy_term_name_depth\Plugin\views\argument\IndexNameDepth::query()
  2. 8.3 src/Plugin/views/argument/IndexNameDepth.php \Drupal\views_taxonomy_term_name_depth\Plugin\views\argument\IndexNameDepth::query()
  3. 7.x src/Plugin/views/argument/IndexNameDepth.php \Drupal\views_taxonomy_term_name_depth\Plugin\views\argument\IndexNameDepth::query()

Set up the query for this argument.

The argument sent may be found at $this->argument.

Overrides ArgumentPluginBase::query

File

src/Plugin/views/argument/IndexNameDepth.php, line 91

Class

IndexNameDepth
Argument handler for taxonomy terms with depth.

Namespace

Drupal\views_taxonomy_term_name_depth\Plugin\views\argument

Code

public function query($group_by = FALSE) {
  $this
    ->ensureMyTable();
  if (!empty($this->options['break_phrase'])) {
    $break = static::breakString($this->argument);
    if ($break->value === array(
      -1,
    )) {
      return FALSE;
    }
    $operator = count($break->value) > 1 ? 'IN' : '=';
    $tids = $break->value;
  }
  else {
    $operator = "=";
    $tids = $this->argument;
  }

  // Now build the subqueries.
  if (is_string($tids)) {

    // Replaces "-" with space if exist.
    $argument = str_replace('-', ' ', $tids);
    $connection = Database::getConnection();
    $query = $connection
      ->select('taxonomy_term_field_data', 't')
      ->fields('t', array(
      'tid',
    ))
      ->condition('t.name', $argument, '=');

    // Execute the statement
    $executed = $query
      ->execute();

    // Get all the results
    $results = $executed
      ->fetchAll(\PDO::FETCH_OBJ);

    // Iterate results
    foreach ($results as $row) {
      $tids = $row->tid;
    }
  }
  $subquery = db_select('taxonomy_index', 'tn');
  $subquery
    ->addField('tn', 'nid');
  $where = db_or()
    ->condition('tn.tid', $tids, $operator);
  $last = "tn";
  if ($this->options['depth'] > 0) {
    $subquery
      ->leftJoin('taxonomy_term_hierarchy', 'th', "th.tid = tn.tid");
    $last = "th";
    foreach (range(1, abs($this->options['depth'])) as $count) {
      $subquery
        ->leftJoin('taxonomy_term_hierarchy', "th{$count}", "{$last}.parent = th{$count}.tid");
      $where
        ->condition("th{$count}.tid", $tids, $operator);
      $last = "th{$count}";
    }
  }
  elseif ($this->options['depth'] < 0) {
    foreach (range(1, abs($this->options['depth'])) as $count) {
      $subquery
        ->leftJoin('taxonomy_term_hierarchy', "th{$count}", "{$last}.tid = th{$count}.parent");
      $where
        ->condition("th{$count}.tid", $tids, $operator);
      $last = "th{$count}";
    }
  }
  $subquery
    ->condition($where);
  $this->query
    ->addWhere(0, "{$this->tableAlias}.{$this->realField}", $subquery, 'IN');
}