annotate core/modules/taxonomy/src/TermStorage.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\taxonomy;
Chris@0 4
Chris@17 5 use Drupal\Core\Entity\EntityInterface;
Chris@0 6 use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
Chris@18 7 use Drupal\Core\Entity\Sql\TableMappingInterface;
Chris@0 8
Chris@0 9 /**
Chris@0 10 * Defines a Controller class for taxonomy terms.
Chris@0 11 */
Chris@0 12 class TermStorage extends SqlContentEntityStorage implements TermStorageInterface {
Chris@0 13
Chris@0 14 /**
Chris@0 15 * Array of term parents keyed by vocabulary ID and child term ID.
Chris@0 16 *
Chris@0 17 * @var array
Chris@0 18 */
Chris@0 19 protected $treeParents = [];
Chris@0 20
Chris@0 21 /**
Chris@0 22 * Array of term ancestors keyed by vocabulary ID and parent term ID.
Chris@0 23 *
Chris@0 24 * @var array
Chris@0 25 */
Chris@0 26 protected $treeChildren = [];
Chris@0 27
Chris@0 28 /**
Chris@0 29 * Array of terms in a tree keyed by vocabulary ID and term ID.
Chris@0 30 *
Chris@0 31 * @var array
Chris@0 32 */
Chris@0 33 protected $treeTerms = [];
Chris@0 34
Chris@0 35 /**
Chris@0 36 * Array of loaded trees keyed by a cache id matching tree arguments.
Chris@0 37 *
Chris@0 38 * @var array
Chris@0 39 */
Chris@0 40 protected $trees = [];
Chris@0 41
Chris@0 42 /**
Chris@17 43 * Array of all loaded term ancestry keyed by ancestor term ID, keyed by term
Chris@17 44 * ID.
Chris@17 45 *
Chris@17 46 * @var \Drupal\taxonomy\TermInterface[][]
Chris@17 47 */
Chris@17 48 protected $ancestors;
Chris@17 49
Chris@17 50 /**
Chris@18 51 * The type of hierarchy allowed within a vocabulary.
Chris@18 52 *
Chris@18 53 * Possible values:
Chris@18 54 * - VocabularyInterface::HIERARCHY_DISABLED: No parents.
Chris@18 55 * - VocabularyInterface::HIERARCHY_SINGLE: Single parent.
Chris@18 56 * - VocabularyInterface::HIERARCHY_MULTIPLE: Multiple parents.
Chris@18 57 *
Chris@18 58 * @var int[]
Chris@18 59 * An array of one the possible values above, keyed by vocabulary ID.
Chris@18 60 */
Chris@18 61 protected $vocabularyHierarchyType;
Chris@18 62
Chris@18 63 /**
Chris@0 64 * {@inheritdoc}
Chris@0 65 *
Chris@0 66 * @param array $values
Chris@0 67 * An array of values to set, keyed by property name. A value for the
Chris@0 68 * vocabulary ID ('vid') is required.
Chris@0 69 */
Chris@0 70 public function create(array $values = []) {
Chris@0 71 // Save new terms with no parents by default.
Chris@0 72 if (empty($values['parent'])) {
Chris@0 73 $values['parent'] = [0];
Chris@0 74 }
Chris@0 75 $entity = parent::create($values);
Chris@0 76 return $entity;
Chris@0 77 }
Chris@0 78
Chris@0 79 /**
Chris@0 80 * {@inheritdoc}
Chris@0 81 */
Chris@0 82 public function resetCache(array $ids = NULL) {
Chris@0 83 drupal_static_reset('taxonomy_term_count_nodes');
Chris@17 84 $this->ancestors = [];
Chris@0 85 $this->treeChildren = [];
Chris@0 86 $this->treeParents = [];
Chris@0 87 $this->treeTerms = [];
Chris@0 88 $this->trees = [];
Chris@18 89 $this->vocabularyHierarchyType = [];
Chris@0 90 parent::resetCache($ids);
Chris@0 91 }
Chris@0 92
Chris@0 93 /**
Chris@0 94 * {@inheritdoc}
Chris@0 95 */
Chris@17 96 public function deleteTermHierarchy($tids) {}
Chris@0 97
Chris@0 98 /**
Chris@0 99 * {@inheritdoc}
Chris@0 100 */
Chris@17 101 public function updateTermHierarchy(EntityInterface $term) {}
Chris@0 102
Chris@0 103 /**
Chris@0 104 * {@inheritdoc}
Chris@0 105 */
Chris@0 106 public function loadParents($tid) {
Chris@17 107 $terms = [];
Chris@17 108 /** @var \Drupal\taxonomy\TermInterface $term */
Chris@17 109 if ($tid && $term = $this->load($tid)) {
Chris@17 110 foreach ($this->getParents($term) as $id => $parent) {
Chris@17 111 // This method currently doesn't return the <root> parent.
Chris@17 112 // @see https://www.drupal.org/node/2019905
Chris@17 113 if (!empty($id)) {
Chris@17 114 $terms[$id] = $parent;
Chris@17 115 }
Chris@0 116 }
Chris@0 117 }
Chris@17 118
Chris@17 119 return $terms;
Chris@17 120 }
Chris@17 121
Chris@17 122 /**
Chris@17 123 * Returns a list of parents of this term.
Chris@17 124 *
Chris@17 125 * @return \Drupal\taxonomy\TermInterface[]
Chris@17 126 * The parent taxonomy term entities keyed by term ID. If this term has a
Chris@17 127 * <root> parent, that item is keyed with 0 and will have NULL as value.
Chris@17 128 *
Chris@17 129 * @internal
Chris@17 130 * @todo Refactor away when TreeInterface is introduced.
Chris@17 131 */
Chris@17 132 protected function getParents(TermInterface $term) {
Chris@17 133 $parents = $ids = [];
Chris@17 134 // Cannot use $this->get('parent')->referencedEntities() here because that
Chris@17 135 // strips out the '0' reference.
Chris@17 136 foreach ($term->get('parent') as $item) {
Chris@17 137 if ($item->target_id == 0) {
Chris@17 138 // The <root> parent.
Chris@17 139 $parents[0] = NULL;
Chris@17 140 continue;
Chris@17 141 }
Chris@17 142 $ids[] = $item->target_id;
Chris@17 143 }
Chris@17 144
Chris@17 145 // @todo Better way to do this? AND handle the NULL/0 parent?
Chris@17 146 // Querying the terms again so that the same access checks are run when
Chris@17 147 // getParents() is called as in Drupal version prior to 8.3.
Chris@17 148 $loaded_parents = [];
Chris@17 149
Chris@17 150 if ($ids) {
Chris@17 151 $query = \Drupal::entityQuery('taxonomy_term')
Chris@17 152 ->condition('tid', $ids, 'IN');
Chris@17 153
Chris@17 154 $loaded_parents = static::loadMultiple($query->execute());
Chris@17 155 }
Chris@17 156
Chris@17 157 return $parents + $loaded_parents;
Chris@0 158 }
Chris@0 159
Chris@0 160 /**
Chris@0 161 * {@inheritdoc}
Chris@0 162 */
Chris@0 163 public function loadAllParents($tid) {
Chris@17 164 /** @var \Drupal\taxonomy\TermInterface $term */
Chris@17 165 return (!empty($tid) && $term = $this->load($tid)) ? $this->getAncestors($term) : [];
Chris@17 166 }
Chris@0 167
Chris@17 168 /**
Chris@17 169 * Returns all ancestors of this term.
Chris@17 170 *
Chris@17 171 * @return \Drupal\taxonomy\TermInterface[]
Chris@17 172 * A list of ancestor taxonomy term entities keyed by term ID.
Chris@17 173 *
Chris@17 174 * @internal
Chris@17 175 * @todo Refactor away when TreeInterface is introduced.
Chris@17 176 */
Chris@17 177 protected function getAncestors(TermInterface $term) {
Chris@17 178 if (!isset($this->ancestors[$term->id()])) {
Chris@17 179 $this->ancestors[$term->id()] = [$term->id() => $term];
Chris@17 180 $search[] = $term->id();
Chris@17 181
Chris@17 182 while ($tid = array_shift($search)) {
Chris@17 183 foreach ($this->getParents(static::load($tid)) as $id => $parent) {
Chris@17 184 if ($parent && !isset($this->ancestors[$term->id()][$id])) {
Chris@17 185 $this->ancestors[$term->id()][$id] = $parent;
Chris@17 186 $search[] = $id;
Chris@0 187 }
Chris@0 188 }
Chris@0 189 }
Chris@0 190 }
Chris@17 191 return $this->ancestors[$term->id()];
Chris@0 192 }
Chris@0 193
Chris@0 194 /**
Chris@0 195 * {@inheritdoc}
Chris@0 196 */
Chris@0 197 public function loadChildren($tid, $vid = NULL) {
Chris@17 198 /** @var \Drupal\taxonomy\TermInterface $term */
Chris@17 199 return (!empty($tid) && $term = $this->load($tid)) ? $this->getChildren($term) : [];
Chris@17 200 }
Chris@17 201
Chris@17 202 /**
Chris@17 203 * Returns all children terms of this term.
Chris@17 204 *
Chris@17 205 * @return \Drupal\taxonomy\TermInterface[]
Chris@17 206 * A list of children taxonomy term entities keyed by term ID.
Chris@17 207 *
Chris@17 208 * @internal
Chris@17 209 * @todo Refactor away when TreeInterface is introduced.
Chris@17 210 */
Chris@17 211 public function getChildren(TermInterface $term) {
Chris@17 212 $query = \Drupal::entityQuery('taxonomy_term')
Chris@17 213 ->condition('parent', $term->id());
Chris@17 214 return static::loadMultiple($query->execute());
Chris@0 215 }
Chris@0 216
Chris@0 217 /**
Chris@0 218 * {@inheritdoc}
Chris@0 219 */
Chris@0 220 public function loadTree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
Chris@0 221 $cache_key = implode(':', func_get_args());
Chris@0 222 if (!isset($this->trees[$cache_key])) {
Chris@0 223 // We cache trees, so it's not CPU-intensive to call on a term and its
Chris@0 224 // children, too.
Chris@0 225 if (!isset($this->treeChildren[$vid])) {
Chris@0 226 $this->treeChildren[$vid] = [];
Chris@0 227 $this->treeParents[$vid] = [];
Chris@0 228 $this->treeTerms[$vid] = [];
Chris@17 229 $query = $this->database->select($this->getDataTable(), 't');
Chris@17 230 $query->join('taxonomy_term__parent', 'p', 't.tid = p.entity_id');
Chris@17 231 $query->addExpression('parent_target_id', 'parent');
Chris@0 232 $result = $query
Chris@0 233 ->addTag('taxonomy_term_access')
Chris@0 234 ->fields('t')
Chris@0 235 ->condition('t.vid', $vid)
Chris@0 236 ->condition('t.default_langcode', 1)
Chris@0 237 ->orderBy('t.weight')
Chris@0 238 ->orderBy('t.name')
Chris@0 239 ->execute();
Chris@0 240 foreach ($result as $term) {
Chris@0 241 $this->treeChildren[$vid][$term->parent][] = $term->tid;
Chris@0 242 $this->treeParents[$vid][$term->tid][] = $term->parent;
Chris@0 243 $this->treeTerms[$vid][$term->tid] = $term;
Chris@0 244 }
Chris@0 245 }
Chris@0 246
Chris@0 247 // Load full entities, if necessary. The entity controller statically
Chris@0 248 // caches the results.
Chris@0 249 $term_entities = [];
Chris@0 250 if ($load_entities) {
Chris@0 251 $term_entities = $this->loadMultiple(array_keys($this->treeTerms[$vid]));
Chris@0 252 }
Chris@0 253
Chris@0 254 $max_depth = (!isset($max_depth)) ? count($this->treeChildren[$vid]) : $max_depth;
Chris@0 255 $tree = [];
Chris@0 256
Chris@0 257 // Keeps track of the parents we have to process, the last entry is used
Chris@0 258 // for the next processing step.
Chris@0 259 $process_parents = [];
Chris@0 260 $process_parents[] = $parent;
Chris@0 261
Chris@0 262 // Loops over the parent terms and adds its children to the tree array.
Chris@0 263 // Uses a loop instead of a recursion, because it's more efficient.
Chris@0 264 while (count($process_parents)) {
Chris@0 265 $parent = array_pop($process_parents);
Chris@0 266 // The number of parents determines the current depth.
Chris@0 267 $depth = count($process_parents);
Chris@0 268 if ($max_depth > $depth && !empty($this->treeChildren[$vid][$parent])) {
Chris@0 269 $has_children = FALSE;
Chris@0 270 $child = current($this->treeChildren[$vid][$parent]);
Chris@0 271 do {
Chris@0 272 if (empty($child)) {
Chris@0 273 break;
Chris@0 274 }
Chris@0 275 $term = $load_entities ? $term_entities[$child] : $this->treeTerms[$vid][$child];
Chris@0 276 if (isset($this->treeParents[$vid][$load_entities ? $term->id() : $term->tid])) {
Chris@0 277 // Clone the term so that the depth attribute remains correct
Chris@0 278 // in the event of multiple parents.
Chris@0 279 $term = clone $term;
Chris@0 280 }
Chris@0 281 $term->depth = $depth;
Chris@17 282 if (!$load_entities) {
Chris@17 283 unset($term->parent);
Chris@17 284 }
Chris@0 285 $tid = $load_entities ? $term->id() : $term->tid;
Chris@0 286 $term->parents = $this->treeParents[$vid][$tid];
Chris@0 287 $tree[] = $term;
Chris@0 288 if (!empty($this->treeChildren[$vid][$tid])) {
Chris@0 289 $has_children = TRUE;
Chris@0 290
Chris@0 291 // We have to continue with this parent later.
Chris@0 292 $process_parents[] = $parent;
Chris@0 293 // Use the current term as parent for the next iteration.
Chris@0 294 $process_parents[] = $tid;
Chris@0 295
Chris@0 296 // Reset pointers for child lists because we step in there more
Chris@0 297 // often with multi parents.
Chris@0 298 reset($this->treeChildren[$vid][$tid]);
Chris@0 299 // Move pointer so that we get the correct term the next time.
Chris@0 300 next($this->treeChildren[$vid][$parent]);
Chris@0 301 break;
Chris@0 302 }
Chris@0 303 } while ($child = next($this->treeChildren[$vid][$parent]));
Chris@0 304
Chris@0 305 if (!$has_children) {
Chris@0 306 // We processed all terms in this hierarchy-level, reset pointer
Chris@0 307 // so that this function works the next time it gets called.
Chris@0 308 reset($this->treeChildren[$vid][$parent]);
Chris@0 309 }
Chris@0 310 }
Chris@0 311 }
Chris@0 312 $this->trees[$cache_key] = $tree;
Chris@0 313 }
Chris@0 314 return $this->trees[$cache_key];
Chris@0 315 }
Chris@0 316
Chris@0 317 /**
Chris@0 318 * {@inheritdoc}
Chris@0 319 */
Chris@0 320 public function nodeCount($vid) {
Chris@0 321 $query = $this->database->select('taxonomy_index', 'ti');
Chris@0 322 $query->addExpression('COUNT(DISTINCT ti.nid)');
Chris@17 323 $query->leftJoin($this->getBaseTable(), 'td', 'ti.tid = td.tid');
Chris@0 324 $query->condition('td.vid', $vid);
Chris@0 325 $query->addTag('vocabulary_node_count');
Chris@0 326 return $query->execute()->fetchField();
Chris@0 327 }
Chris@0 328
Chris@0 329 /**
Chris@0 330 * {@inheritdoc}
Chris@0 331 */
Chris@0 332 public function resetWeights($vid) {
Chris@17 333 $this->database->update($this->getDataTable())
Chris@0 334 ->fields(['weight' => 0])
Chris@0 335 ->condition('vid', $vid)
Chris@0 336 ->execute();
Chris@0 337 }
Chris@0 338
Chris@0 339 /**
Chris@0 340 * {@inheritdoc}
Chris@0 341 */
Chris@0 342 public function getNodeTerms(array $nids, array $vocabs = [], $langcode = NULL) {
Chris@18 343 $query = $this->database->select($this->getDataTable(), 'td');
Chris@0 344 $query->innerJoin('taxonomy_index', 'tn', 'td.tid = tn.tid');
Chris@0 345 $query->fields('td', ['tid']);
Chris@0 346 $query->addField('tn', 'nid', 'node_nid');
Chris@0 347 $query->orderby('td.weight');
Chris@0 348 $query->orderby('td.name');
Chris@0 349 $query->condition('tn.nid', $nids, 'IN');
Chris@0 350 $query->addTag('taxonomy_term_access');
Chris@0 351 if (!empty($vocabs)) {
Chris@0 352 $query->condition('td.vid', $vocabs, 'IN');
Chris@0 353 }
Chris@0 354 if (!empty($langcode)) {
Chris@0 355 $query->condition('td.langcode', $langcode);
Chris@0 356 }
Chris@0 357
Chris@0 358 $results = [];
Chris@0 359 $all_tids = [];
Chris@0 360 foreach ($query->execute() as $term_record) {
Chris@0 361 $results[$term_record->node_nid][] = $term_record->tid;
Chris@0 362 $all_tids[] = $term_record->tid;
Chris@0 363 }
Chris@0 364
Chris@0 365 $all_terms = $this->loadMultiple($all_tids);
Chris@0 366 $terms = [];
Chris@0 367 foreach ($results as $nid => $tids) {
Chris@0 368 foreach ($tids as $tid) {
Chris@0 369 $terms[$nid][$tid] = $all_terms[$tid];
Chris@0 370 }
Chris@0 371 }
Chris@0 372 return $terms;
Chris@0 373 }
Chris@0 374
Chris@0 375 /**
Chris@0 376 * {@inheritdoc}
Chris@0 377 */
Chris@18 378 public function getTermIdsWithPendingRevisions() {
Chris@18 379 $table_mapping = $this->getTableMapping();
Chris@18 380 $id_field = $table_mapping->getColumnNames($this->entityType->getKey('id'))['value'];
Chris@18 381 $revision_field = $table_mapping->getColumnNames($this->entityType->getKey('revision'))['value'];
Chris@18 382 $rta_field = $table_mapping->getColumnNames($this->entityType->getKey('revision_translation_affected'))['value'];
Chris@18 383 $langcode_field = $table_mapping->getColumnNames($this->entityType->getKey('langcode'))['value'];
Chris@18 384 $revision_default_field = $table_mapping->getColumnNames($this->entityType->getRevisionMetadataKey('revision_default'))['value'];
Chris@18 385
Chris@18 386 $query = $this->database->select($this->getRevisionDataTable(), 'tfr');
Chris@18 387 $query->fields('tfr', [$id_field]);
Chris@18 388 $query->addExpression("MAX(tfr.$revision_field)", $revision_field);
Chris@18 389
Chris@18 390 $query->join($this->getRevisionTable(), 'tr', "tfr.$revision_field = tr.$revision_field AND tr.$revision_default_field = 0");
Chris@18 391
Chris@18 392 $inner_select = $this->database->select($this->getRevisionDataTable(), 't');
Chris@18 393 $inner_select->condition("t.$rta_field", '1');
Chris@18 394 $inner_select->fields('t', [$id_field, $langcode_field]);
Chris@18 395 $inner_select->addExpression("MAX(t.$revision_field)", $revision_field);
Chris@18 396 $inner_select
Chris@18 397 ->groupBy("t.$id_field")
Chris@18 398 ->groupBy("t.$langcode_field");
Chris@18 399
Chris@18 400 $query->join($inner_select, 'mr', "tfr.$revision_field = mr.$revision_field AND tfr.$langcode_field = mr.$langcode_field");
Chris@18 401
Chris@18 402 $query->groupBy("tfr.$id_field");
Chris@18 403
Chris@18 404 return $query->execute()->fetchAllKeyed(1, 0);
Chris@18 405 }
Chris@18 406
Chris@18 407 /**
Chris@18 408 * {@inheritdoc}
Chris@18 409 */
Chris@18 410 public function getVocabularyHierarchyType($vid) {
Chris@18 411 // Return early if we already computed this value.
Chris@18 412 if (isset($this->vocabularyHierarchyType[$vid])) {
Chris@18 413 return $this->vocabularyHierarchyType[$vid];
Chris@18 414 }
Chris@18 415
Chris@18 416 $parent_field_storage = $this->entityFieldManager->getFieldStorageDefinitions($this->entityTypeId)['parent'];
Chris@18 417 $table_mapping = $this->getTableMapping();
Chris@18 418
Chris@18 419 $target_id_column = $table_mapping->getFieldColumnName($parent_field_storage, 'target_id');
Chris@18 420 $delta_column = $table_mapping->getFieldColumnName($parent_field_storage, TableMappingInterface::DELTA);
Chris@18 421
Chris@18 422 $query = $this->database->select($table_mapping->getFieldTableName('parent'), 'p');
Chris@18 423 $query->addExpression("MAX($target_id_column)", 'max_parent_id');
Chris@18 424 $query->addExpression("MAX($delta_column)", 'max_delta');
Chris@18 425 $query->condition('bundle', $vid);
Chris@18 426
Chris@18 427 $result = $query->execute()->fetchAll();
Chris@18 428
Chris@18 429 // If all the terms have the same parent, the parent can only be root (0).
Chris@18 430 if ((int) $result[0]->max_parent_id === 0) {
Chris@18 431 $this->vocabularyHierarchyType[$vid] = VocabularyInterface::HIERARCHY_DISABLED;
Chris@18 432 }
Chris@18 433 // If no term has a delta higher than 0, no term has multiple parents.
Chris@18 434 elseif ((int) $result[0]->max_delta === 0) {
Chris@18 435 $this->vocabularyHierarchyType[$vid] = VocabularyInterface::HIERARCHY_SINGLE;
Chris@18 436 }
Chris@18 437 else {
Chris@18 438 $this->vocabularyHierarchyType[$vid] = VocabularyInterface::HIERARCHY_MULTIPLE;
Chris@18 439 }
Chris@18 440
Chris@18 441 return $this->vocabularyHierarchyType[$vid];
Chris@18 442 }
Chris@18 443
Chris@18 444 /**
Chris@18 445 * {@inheritdoc}
Chris@18 446 */
Chris@0 447 public function __sleep() {
Chris@0 448 $vars = parent::__sleep();
Chris@0 449 // Do not serialize static cache.
Chris@18 450 unset($vars['ancestors'], $vars['treeChildren'], $vars['treeParents'], $vars['treeTerms'], $vars['trees'], $vars['vocabularyHierarchyType']);
Chris@0 451 return $vars;
Chris@0 452 }
Chris@0 453
Chris@0 454 /**
Chris@0 455 * {@inheritdoc}
Chris@0 456 */
Chris@0 457 public function __wakeup() {
Chris@0 458 parent::__wakeup();
Chris@0 459 // Initialize static caches.
Chris@17 460 $this->ancestors = [];
Chris@0 461 $this->treeChildren = [];
Chris@0 462 $this->treeParents = [];
Chris@0 463 $this->treeTerms = [];
Chris@0 464 $this->trees = [];
Chris@18 465 $this->vocabularyHierarchyType = [];
Chris@0 466 }
Chris@0 467
Chris@0 468 }