TermStorage.php 11.2 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\taxonomy;

5
use Drupal\Core\Entity\EntityInterface;
6
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
7 8 9 10

/**
 * Defines a Controller class for taxonomy terms.
 */
11
class TermStorage extends SqlContentEntityStorage implements TermStorageInterface {
12

13 14 15 16 17
  /**
   * Array of term parents keyed by vocabulary ID and child term ID.
   *
   * @var array
   */
18
  protected $treeParents = [];
19 20 21 22 23 24

  /**
   * Array of term ancestors keyed by vocabulary ID and parent term ID.
   *
   * @var array
   */
25
  protected $treeChildren = [];
26 27 28 29 30 31

  /**
   * Array of terms in a tree keyed by vocabulary ID and term ID.
   *
   * @var array
   */
32
  protected $treeTerms = [];
33 34 35 36 37 38

  /**
   * Array of loaded trees keyed by a cache id matching tree arguments.
   *
   * @var array
   */
39
  protected $trees = [];
40

41 42 43 44 45 46 47 48
  /**
   * Array of all loaded term ancestry keyed by ancestor term ID, keyed by term
   * ID.
   *
   * @var \Drupal\taxonomy\TermInterface[][]
   */
  protected $ancestors;

49
  /**
50
   * {@inheritdoc}
51 52 53 54 55
   *
   * @param array $values
   *   An array of values to set, keyed by property name. A value for the
   *   vocabulary ID ('vid') is required.
   */
56
  public function create(array $values = []) {
57
    // Save new terms with no parents by default.
58
    if (empty($values['parent'])) {
59
      $values['parent'] = [0];
60
    }
61
    $entity = parent::create($values);
62 63 64 65
    return $entity;
  }

  /**
66
   * {@inheritdoc}
67 68 69
   */
  public function resetCache(array $ids = NULL) {
    drupal_static_reset('taxonomy_term_count_nodes');
70
    $this->ancestors = [];
71 72 73 74
    $this->treeChildren = [];
    $this->treeParents = [];
    $this->treeTerms = [];
    $this->trees = [];
75 76
    parent::resetCache($ids);
  }
77

78 79 80
  /**
   * {@inheritdoc}
   */
81
  public function deleteTermHierarchy($tids) {}
82 83 84 85

  /**
   * {@inheritdoc}
   */
86
  public function updateTermHierarchy(EntityInterface $term) {}
87

88 89 90 91
  /**
   * {@inheritdoc}
   */
  public function loadParents($tid) {
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    $terms = [];
    /** @var \Drupal\taxonomy\TermInterface $term */
    if ($tid && $term = $this->load($tid)) {
      foreach ($this->getParents($term) as $id => $parent) {
        // This method currently doesn't return the <root> parent.
        // @see https://www.drupal.org/node/2019905
        if (!empty($id)) {
          $terms[$id] = $parent;
        }
      }
    }

    return $terms;
  }

  /**
   * Returns a list of parents of this term.
   *
   * @return \Drupal\taxonomy\TermInterface[]
   *   The parent taxonomy term entities keyed by term ID. If this term has a
   *   <root> parent, that item is keyed with 0 and will have NULL as value.
   *
   * @internal
   * @todo Refactor away when TreeInterface is introduced.
   */
  protected function getParents(TermInterface $term) {
    $parents = $ids = [];
    // Cannot use $this->get('parent')->referencedEntities() here because that
    // strips out the '0' reference.
    foreach ($term->get('parent') as $item) {
      if ($item->target_id == 0) {
        // The <root> parent.
        $parents[0] = NULL;
        continue;
126
      }
127
      $ids[] = $item->target_id;
128
    }
129 130 131 132 133 134 135 136 137 138 139 140 141 142

    // @todo Better way to do this? AND handle the NULL/0 parent?
    // Querying the terms again so that the same access checks are run when
    // getParents() is called as in Drupal version prior to 8.3.
    $loaded_parents = [];

    if ($ids) {
      $query = \Drupal::entityQuery('taxonomy_term')
        ->condition('tid', $ids, 'IN');

      $loaded_parents = static::loadMultiple($query->execute());
    }

    return $parents + $loaded_parents;
143 144 145 146 147 148
  }

  /**
   * {@inheritdoc}
   */
  public function loadAllParents($tid) {
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    /** @var \Drupal\taxonomy\TermInterface $term */
    return (!empty($tid) && $term = $this->load($tid)) ? $this->getAncestors($term) : [];
  }

  /**
   * Returns all ancestors of this term.
   *
   * @return \Drupal\taxonomy\TermInterface[]
   *   A list of ancestor taxonomy term entities keyed by term ID.
   *
   * @internal
   * @todo Refactor away when TreeInterface is introduced.
   */
  protected function getAncestors(TermInterface $term) {
    if (!isset($this->ancestors[$term->id()])) {
      $this->ancestors[$term->id()] = [$term->id() => $term];
      $search[] = $term->id();

      while ($tid = array_shift($search)) {
        foreach ($this->getParents(static::load($tid)) as $id => $parent) {
          if ($parent && !isset($this->ancestors[$term->id()][$id])) {
            $this->ancestors[$term->id()][$id] = $parent;
            $search[] = $id;
172
          }
173 174 175
        }
      }
    }
176
    return $this->ancestors[$term->id()];
177 178 179 180 181 182
  }

  /**
   * {@inheritdoc}
   */
  public function loadChildren($tid, $vid = NULL) {
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    /** @var \Drupal\taxonomy\TermInterface $term */
    return (!empty($tid) && $term = $this->load($tid)) ? $this->getChildren($term) : [];
  }

  /**
   * Returns all children terms of this term.
   *
   * @return \Drupal\taxonomy\TermInterface[]
   *   A list of children taxonomy term entities keyed by term ID.
   *
   * @internal
   * @todo Refactor away when TreeInterface is introduced.
   */
  public function getChildren(TermInterface $term) {
    $query = \Drupal::entityQuery('taxonomy_term')
      ->condition('parent', $term->id());
    return static::loadMultiple($query->execute());
200 201 202 203 204
  }

  /**
   * {@inheritdoc}
   */
205 206 207 208 209 210
  public function loadTree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
    $cache_key = implode(':', func_get_args());
    if (!isset($this->trees[$cache_key])) {
      // We cache trees, so it's not CPU-intensive to call on a term and its
      // children, too.
      if (!isset($this->treeChildren[$vid])) {
211 212 213
        $this->treeChildren[$vid] = [];
        $this->treeParents[$vid] = [];
        $this->treeTerms[$vid] = [];
214
        $query = $this->database->select($this->getDataTable(), 't');
215 216
        $query->join('taxonomy_term__parent', 'p', 't.tid = p.entity_id');
        $query->addExpression('parent_target_id', 'parent');
217
        $result = $query
218
          ->addTag('taxonomy_term_access')
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
          ->fields('t')
          ->condition('t.vid', $vid)
          ->condition('t.default_langcode', 1)
          ->orderBy('t.weight')
          ->orderBy('t.name')
          ->execute();
        foreach ($result as $term) {
          $this->treeChildren[$vid][$term->parent][] = $term->tid;
          $this->treeParents[$vid][$term->tid][] = $term->parent;
          $this->treeTerms[$vid][$term->tid] = $term;
        }
      }

      // Load full entities, if necessary. The entity controller statically
      // caches the results.
234
      $term_entities = [];
235 236 237 238 239
      if ($load_entities) {
        $term_entities = $this->loadMultiple(array_keys($this->treeTerms[$vid]));
      }

      $max_depth = (!isset($max_depth)) ? count($this->treeChildren[$vid]) : $max_depth;
240
      $tree = [];
241 242 243

      // Keeps track of the parents we have to process, the last entry is used
      // for the next processing step.
244
      $process_parents = [];
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
      $process_parents[] = $parent;

      // Loops over the parent terms and adds its children to the tree array.
      // Uses a loop instead of a recursion, because it's more efficient.
      while (count($process_parents)) {
        $parent = array_pop($process_parents);
        // The number of parents determines the current depth.
        $depth = count($process_parents);
        if ($max_depth > $depth && !empty($this->treeChildren[$vid][$parent])) {
          $has_children = FALSE;
          $child = current($this->treeChildren[$vid][$parent]);
          do {
            if (empty($child)) {
              break;
            }
            $term = $load_entities ? $term_entities[$child] : $this->treeTerms[$vid][$child];
            if (isset($this->treeParents[$vid][$load_entities ? $term->id() : $term->tid])) {
              // Clone the term so that the depth attribute remains correct
              // in the event of multiple parents.
              $term = clone $term;
            }
            $term->depth = $depth;
267 268 269
            if (!$load_entities) {
              unset($term->parent);
            }
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
            $tid = $load_entities ? $term->id() : $term->tid;
            $term->parents = $this->treeParents[$vid][$tid];
            $tree[] = $term;
            if (!empty($this->treeChildren[$vid][$tid])) {
              $has_children = TRUE;

              // We have to continue with this parent later.
              $process_parents[] = $parent;
              // Use the current term as parent for the next iteration.
              $process_parents[] = $tid;

              // Reset pointers for child lists because we step in there more
              // often with multi parents.
              reset($this->treeChildren[$vid][$tid]);
              // Move pointer so that we get the correct term the next time.
              next($this->treeChildren[$vid][$parent]);
              break;
            }
          } while ($child = next($this->treeChildren[$vid][$parent]));

          if (!$has_children) {
            // We processed all terms in this hierarchy-level, reset pointer
            // so that this function works the next time it gets called.
            reset($this->treeChildren[$vid][$parent]);
          }
        }
      }
      $this->trees[$cache_key] = $tree;
    }
    return $this->trees[$cache_key];
300 301 302 303 304 305 306 307
  }

  /**
   * {@inheritdoc}
   */
  public function nodeCount($vid) {
    $query = $this->database->select('taxonomy_index', 'ti');
    $query->addExpression('COUNT(DISTINCT ti.nid)');
308
    $query->leftJoin($this->getBaseTable(), 'td', 'ti.tid = td.tid');
309 310 311 312 313 314 315 316 317
    $query->condition('td.vid', $vid);
    $query->addTag('vocabulary_node_count');
    return $query->execute()->fetchField();
  }

  /**
   * {@inheritdoc}
   */
  public function resetWeights($vid) {
318
    $this->database->update($this->getDataTable())
319
      ->fields(['weight' => 0])
320 321 322 323
      ->condition('vid', $vid)
      ->execute();
  }

324 325 326
  /**
   * {@inheritdoc}
   */
327
  public function getNodeTerms(array $nids, array $vocabs = [], $langcode = NULL) {
328
    $query = db_select($this->getDataTable(), 'td');
329
    $query->innerJoin('taxonomy_index', 'tn', 'td.tid = tn.tid');
330
    $query->fields('td', ['tid']);
331 332 333
    $query->addField('tn', 'nid', 'node_nid');
    $query->orderby('td.weight');
    $query->orderby('td.name');
334
    $query->condition('tn.nid', $nids, 'IN');
335
    $query->addTag('taxonomy_term_access');
336
    if (!empty($vocabs)) {
337
      $query->condition('td.vid', $vocabs, 'IN');
338 339 340 341 342
    }
    if (!empty($langcode)) {
      $query->condition('td.langcode', $langcode);
    }

343 344
    $results = [];
    $all_tids = [];
345 346 347 348 349 350
    foreach ($query->execute() as $term_record) {
      $results[$term_record->node_nid][] = $term_record->tid;
      $all_tids[] = $term_record->tid;
    }

    $all_terms = $this->loadMultiple($all_tids);
351
    $terms = [];
352 353
    foreach ($results as $nid => $tids) {
      foreach ($tids as $tid) {
354
        $terms[$nid][$tid] = $all_terms[$tid];
355 356 357 358 359
      }
    }
    return $terms;
  }

360 361 362 363 364 365
  /**
   * {@inheritdoc}
   */
  public function __sleep() {
    $vars = parent::__sleep();
    // Do not serialize static cache.
366
    unset($vars['treeChildren'], $vars['treeParents'], $vars['treeTerms'], $vars['trees']);
367 368 369 370 371 372 373 374 375
    return $vars;
  }

  /**
   * {@inheritdoc}
   */
  public function __wakeup() {
    parent::__wakeup();
    // Initialize static caches.
376
    $this->ancestors = [];
377 378 379 380
    $this->treeChildren = [];
    $this->treeParents = [];
    $this->treeTerms = [];
    $this->trees = [];
381 382
  }

383
}