3 namespace Drupal\taxonomy;
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
9 * Defines a Controller class for taxonomy terms.
11 class TermStorage extends SqlContentEntityStorage implements TermStorageInterface {
14 * Array of term parents keyed by vocabulary ID and child term ID.
18 protected $treeParents = [];
21 * Array of term ancestors keyed by vocabulary ID and parent term ID.
25 protected $treeChildren = [];
28 * Array of terms in a tree keyed by vocabulary ID and term ID.
32 protected $treeTerms = [];
35 * Array of loaded trees keyed by a cache id matching tree arguments.
39 protected $trees = [];
42 * Array of all loaded term ancestry keyed by ancestor term ID, keyed by term
45 * @var \Drupal\taxonomy\TermInterface[][]
52 * @param array $values
53 * An array of values to set, keyed by property name. A value for the
54 * 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];
61 $entity = parent::create($values);
68 public function resetCache(array $ids = NULL) {
69 drupal_static_reset('taxonomy_term_count_nodes');
70 $this->ancestors = [];
71 $this->treeChildren = [];
72 $this->treeParents = [];
73 $this->treeTerms = [];
75 parent::resetCache($ids);
81 public function deleteTermHierarchy($tids) {}
86 public function updateTermHierarchy(EntityInterface $term) {}
91 public function loadParents($tid) {
93 /** @var \Drupal\taxonomy\TermInterface $term */
94 if ($tid && $term = $this->load($tid)) {
95 foreach ($this->getParents($term) as $id => $parent) {
96 // This method currently doesn't return the <root> parent.
97 // @see https://www.drupal.org/node/2019905
99 $terms[$id] = $parent;
108 * Returns a list of parents of this term.
110 * @return \Drupal\taxonomy\TermInterface[]
111 * The parent taxonomy term entities keyed by term ID. If this term has a
112 * <root> parent, that item is keyed with 0 and will have NULL as value.
115 * @todo Refactor away when TreeInterface is introduced.
117 protected function getParents(TermInterface $term) {
118 $parents = $ids = [];
119 // Cannot use $this->get('parent')->referencedEntities() here because that
120 // strips out the '0' reference.
121 foreach ($term->get('parent') as $item) {
122 if ($item->target_id == 0) {
123 // The <root> parent.
127 $ids[] = $item->target_id;
130 // @todo Better way to do this? AND handle the NULL/0 parent?
131 // Querying the terms again so that the same access checks are run when
132 // getParents() is called as in Drupal version prior to 8.3.
133 $loaded_parents = [];
136 $query = \Drupal::entityQuery('taxonomy_term')
137 ->condition('tid', $ids, 'IN');
139 $loaded_parents = static::loadMultiple($query->execute());
142 return $parents + $loaded_parents;
148 public function loadAllParents($tid) {
149 /** @var \Drupal\taxonomy\TermInterface $term */
150 return (!empty($tid) && $term = $this->load($tid)) ? $this->getAncestors($term) : [];
154 * Returns all ancestors of this term.
156 * @return \Drupal\taxonomy\TermInterface[]
157 * A list of ancestor taxonomy term entities keyed by term ID.
160 * @todo Refactor away when TreeInterface is introduced.
162 protected function getAncestors(TermInterface $term) {
163 if (!isset($this->ancestors[$term->id()])) {
164 $this->ancestors[$term->id()] = [$term->id() => $term];
165 $search[] = $term->id();
167 while ($tid = array_shift($search)) {
168 foreach ($this->getParents(static::load($tid)) as $id => $parent) {
169 if ($parent && !isset($this->ancestors[$term->id()][$id])) {
170 $this->ancestors[$term->id()][$id] = $parent;
176 return $this->ancestors[$term->id()];
182 public function loadChildren($tid, $vid = NULL) {
183 /** @var \Drupal\taxonomy\TermInterface $term */
184 return (!empty($tid) && $term = $this->load($tid)) ? $this->getChildren($term) : [];
188 * Returns all children terms of this term.
190 * @return \Drupal\taxonomy\TermInterface[]
191 * A list of children taxonomy term entities keyed by term ID.
194 * @todo Refactor away when TreeInterface is introduced.
196 public function getChildren(TermInterface $term) {
197 $query = \Drupal::entityQuery('taxonomy_term')
198 ->condition('parent', $term->id());
199 return static::loadMultiple($query->execute());
205 public function loadTree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
206 $cache_key = implode(':', func_get_args());
207 if (!isset($this->trees[$cache_key])) {
208 // We cache trees, so it's not CPU-intensive to call on a term and its
210 if (!isset($this->treeChildren[$vid])) {
211 $this->treeChildren[$vid] = [];
212 $this->treeParents[$vid] = [];
213 $this->treeTerms[$vid] = [];
214 $query = $this->database->select($this->getDataTable(), 't');
215 $query->join('taxonomy_term__parent', 'p', 't.tid = p.entity_id');
216 $query->addExpression('parent_target_id', 'parent');
218 ->addTag('taxonomy_term_access')
220 ->condition('t.vid', $vid)
221 ->condition('t.default_langcode', 1)
222 ->orderBy('t.weight')
225 foreach ($result as $term) {
226 $this->treeChildren[$vid][$term->parent][] = $term->tid;
227 $this->treeParents[$vid][$term->tid][] = $term->parent;
228 $this->treeTerms[$vid][$term->tid] = $term;
232 // Load full entities, if necessary. The entity controller statically
233 // caches the results.
235 if ($load_entities) {
236 $term_entities = $this->loadMultiple(array_keys($this->treeTerms[$vid]));
239 $max_depth = (!isset($max_depth)) ? count($this->treeChildren[$vid]) : $max_depth;
242 // Keeps track of the parents we have to process, the last entry is used
243 // for the next processing step.
244 $process_parents = [];
245 $process_parents[] = $parent;
247 // Loops over the parent terms and adds its children to the tree array.
248 // Uses a loop instead of a recursion, because it's more efficient.
249 while (count($process_parents)) {
250 $parent = array_pop($process_parents);
251 // The number of parents determines the current depth.
252 $depth = count($process_parents);
253 if ($max_depth > $depth && !empty($this->treeChildren[$vid][$parent])) {
254 $has_children = FALSE;
255 $child = current($this->treeChildren[$vid][$parent]);
260 $term = $load_entities ? $term_entities[$child] : $this->treeTerms[$vid][$child];
261 if (isset($this->treeParents[$vid][$load_entities ? $term->id() : $term->tid])) {
262 // Clone the term so that the depth attribute remains correct
263 // in the event of multiple parents.
266 $term->depth = $depth;
267 if (!$load_entities) {
268 unset($term->parent);
270 $tid = $load_entities ? $term->id() : $term->tid;
271 $term->parents = $this->treeParents[$vid][$tid];
273 if (!empty($this->treeChildren[$vid][$tid])) {
274 $has_children = TRUE;
276 // We have to continue with this parent later.
277 $process_parents[] = $parent;
278 // Use the current term as parent for the next iteration.
279 $process_parents[] = $tid;
281 // Reset pointers for child lists because we step in there more
282 // often with multi parents.
283 reset($this->treeChildren[$vid][$tid]);
284 // Move pointer so that we get the correct term the next time.
285 next($this->treeChildren[$vid][$parent]);
288 } while ($child = next($this->treeChildren[$vid][$parent]));
290 if (!$has_children) {
291 // We processed all terms in this hierarchy-level, reset pointer
292 // so that this function works the next time it gets called.
293 reset($this->treeChildren[$vid][$parent]);
297 $this->trees[$cache_key] = $tree;
299 return $this->trees[$cache_key];
305 public function nodeCount($vid) {
306 $query = $this->database->select('taxonomy_index', 'ti');
307 $query->addExpression('COUNT(DISTINCT ti.nid)');
308 $query->leftJoin($this->getBaseTable(), 'td', 'ti.tid = td.tid');
309 $query->condition('td.vid', $vid);
310 $query->addTag('vocabulary_node_count');
311 return $query->execute()->fetchField();
317 public function resetWeights($vid) {
318 $this->database->update($this->getDataTable())
319 ->fields(['weight' => 0])
320 ->condition('vid', $vid)
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 $query->addField('tn', 'nid', 'node_nid');
332 $query->orderby('td.weight');
333 $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');
339 if (!empty($langcode)) {
340 $query->condition('td.langcode', $langcode);
345 foreach ($query->execute() as $term_record) {
346 $results[$term_record->node_nid][] = $term_record->tid;
347 $all_tids[] = $term_record->tid;
350 $all_terms = $this->loadMultiple($all_tids);
352 foreach ($results as $nid => $tids) {
353 foreach ($tids as $tid) {
354 $terms[$nid][$tid] = $all_terms[$tid];
363 public function __sleep() {
364 $vars = parent::__sleep();
365 // Do not serialize static cache.
366 unset($vars['ancestors'], $vars['treeChildren'], $vars['treeParents'], $vars['treeTerms'], $vars['trees']);
373 public function __wakeup() {
375 // Initialize static caches.
376 $this->ancestors = [];
377 $this->treeChildren = [];
378 $this->treeParents = [];
379 $this->treeTerms = [];