2d47722faeae5350efbd3118b9a99ce7d681f942
[yaffs-website] / web / core / modules / taxonomy / src / TermStorage.php
1 <?php
2
3 namespace Drupal\taxonomy;
4
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
7
8 /**
9  * Defines a Controller class for taxonomy terms.
10  */
11 class TermStorage extends SqlContentEntityStorage implements TermStorageInterface {
12
13   /**
14    * Array of term parents keyed by vocabulary ID and child term ID.
15    *
16    * @var array
17    */
18   protected $treeParents = [];
19
20   /**
21    * Array of term ancestors keyed by vocabulary ID and parent term ID.
22    *
23    * @var array
24    */
25   protected $treeChildren = [];
26
27   /**
28    * Array of terms in a tree keyed by vocabulary ID and term ID.
29    *
30    * @var array
31    */
32   protected $treeTerms = [];
33
34   /**
35    * Array of loaded trees keyed by a cache id matching tree arguments.
36    *
37    * @var array
38    */
39   protected $trees = [];
40
41   /**
42    * Array of all loaded term ancestry keyed by ancestor term ID, keyed by term
43    * ID.
44    *
45    * @var \Drupal\taxonomy\TermInterface[][]
46    */
47   protected $ancestors;
48
49   /**
50    * {@inheritdoc}
51    *
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.
55    */
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     return $entity;
63   }
64
65   /**
66    * {@inheritdoc}
67    */
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 = [];
74     $this->trees = [];
75     parent::resetCache($ids);
76   }
77
78   /**
79    * {@inheritdoc}
80    */
81   public function deleteTermHierarchy($tids) {}
82
83   /**
84    * {@inheritdoc}
85    */
86   public function updateTermHierarchy(EntityInterface $term) {}
87
88   /**
89    * {@inheritdoc}
90    */
91   public function loadParents($tid) {
92     $terms = [];
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
98         if (!empty($id)) {
99           $terms[$id] = $parent;
100         }
101       }
102     }
103
104     return $terms;
105   }
106
107   /**
108    * Returns a list of parents of this term.
109    *
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.
113    *
114    * @internal
115    * @todo Refactor away when TreeInterface is introduced.
116    */
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.
124         $parents[0] = NULL;
125         continue;
126       }
127       $ids[] = $item->target_id;
128     }
129
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 = [];
134
135     if ($ids) {
136       $query = \Drupal::entityQuery('taxonomy_term')
137         ->condition('tid', $ids, 'IN');
138
139       $loaded_parents = static::loadMultiple($query->execute());
140     }
141
142     return $parents + $loaded_parents;
143   }
144
145   /**
146    * {@inheritdoc}
147    */
148   public function loadAllParents($tid) {
149     /** @var \Drupal\taxonomy\TermInterface $term */
150     return (!empty($tid) && $term = $this->load($tid)) ? $this->getAncestors($term) : [];
151   }
152
153   /**
154    * Returns all ancestors of this term.
155    *
156    * @return \Drupal\taxonomy\TermInterface[]
157    *   A list of ancestor taxonomy term entities keyed by term ID.
158    *
159    * @internal
160    * @todo Refactor away when TreeInterface is introduced.
161    */
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();
166
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;
171             $search[] = $id;
172           }
173         }
174       }
175     }
176     return $this->ancestors[$term->id()];
177   }
178
179   /**
180    * {@inheritdoc}
181    */
182   public function loadChildren($tid, $vid = NULL) {
183     /** @var \Drupal\taxonomy\TermInterface $term */
184     return (!empty($tid) && $term = $this->load($tid)) ? $this->getChildren($term) : [];
185   }
186
187   /**
188    * Returns all children terms of this term.
189    *
190    * @return \Drupal\taxonomy\TermInterface[]
191    *   A list of children taxonomy term entities keyed by term ID.
192    *
193    * @internal
194    * @todo Refactor away when TreeInterface is introduced.
195    */
196   public function getChildren(TermInterface $term) {
197     $query = \Drupal::entityQuery('taxonomy_term')
198       ->condition('parent', $term->id());
199     return static::loadMultiple($query->execute());
200   }
201
202   /**
203    * {@inheritdoc}
204    */
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
209       // children, too.
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');
217         $result = $query
218           ->addTag('taxonomy_term_access')
219           ->fields('t')
220           ->condition('t.vid', $vid)
221           ->condition('t.default_langcode', 1)
222           ->orderBy('t.weight')
223           ->orderBy('t.name')
224           ->execute();
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;
229         }
230       }
231
232       // Load full entities, if necessary. The entity controller statically
233       // caches the results.
234       $term_entities = [];
235       if ($load_entities) {
236         $term_entities = $this->loadMultiple(array_keys($this->treeTerms[$vid]));
237       }
238
239       $max_depth = (!isset($max_depth)) ? count($this->treeChildren[$vid]) : $max_depth;
240       $tree = [];
241
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;
246
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]);
256           do {
257             if (empty($child)) {
258               break;
259             }
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.
264               $term = clone $term;
265             }
266             $term->depth = $depth;
267             if (!$load_entities) {
268               unset($term->parent);
269             }
270             $tid = $load_entities ? $term->id() : $term->tid;
271             $term->parents = $this->treeParents[$vid][$tid];
272             $tree[] = $term;
273             if (!empty($this->treeChildren[$vid][$tid])) {
274               $has_children = TRUE;
275
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;
280
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]);
286               break;
287             }
288           } while ($child = next($this->treeChildren[$vid][$parent]));
289
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]);
294           }
295         }
296       }
297       $this->trees[$cache_key] = $tree;
298     }
299     return $this->trees[$cache_key];
300   }
301
302   /**
303    * {@inheritdoc}
304    */
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();
312   }
313
314   /**
315    * {@inheritdoc}
316    */
317   public function resetWeights($vid) {
318     $this->database->update($this->getDataTable())
319       ->fields(['weight' => 0])
320       ->condition('vid', $vid)
321       ->execute();
322   }
323
324   /**
325    * {@inheritdoc}
326    */
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');
338     }
339     if (!empty($langcode)) {
340       $query->condition('td.langcode', $langcode);
341     }
342
343     $results = [];
344     $all_tids = [];
345     foreach ($query->execute() as $term_record) {
346       $results[$term_record->node_nid][] = $term_record->tid;
347       $all_tids[] = $term_record->tid;
348     }
349
350     $all_terms = $this->loadMultiple($all_tids);
351     $terms = [];
352     foreach ($results as $nid => $tids) {
353       foreach ($tids as $tid) {
354         $terms[$nid][$tid] = $all_terms[$tid];
355       }
356     }
357     return $terms;
358   }
359
360   /**
361    * {@inheritdoc}
362    */
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']);
367     return $vars;
368   }
369
370   /**
371    * {@inheritdoc}
372    */
373   public function __wakeup() {
374     parent::__wakeup();
375     // Initialize static caches.
376     $this->ancestors = [];
377     $this->treeChildren = [];
378     $this->treeParents = [];
379     $this->treeTerms = [];
380     $this->trees = [];
381   }
382
383 }