You are here

protected function TaxonomyTermTree::buildTree in Organigrams 8

Same name and namespace in other branches
  1. 8.2 src/TaxonomyTermTree.php \Drupal\organigrams\TaxonomyTermTree::buildTree()

Populates a tree array given a taxonomy term tree object.

Parameters

array $tree: Contains the tree so far.

object $object: Contains a taxonomy term possibly with children.

string $vocabulary: Contains the vocabulary machine name.

1 call to TaxonomyTermTree::buildTree()
TaxonomyTermTree::load in src/TaxonomyTermTree.php
Loads the tree of a vocabulary.

File

src/TaxonomyTermTree.php, line 75

Class

TaxonomyTermTree
Loads taxonomy terms in a tree.

Namespace

Drupal\organigrams

Code

protected function buildTree(array &$tree, $object, $vocabulary) {

  // Do nothing when depth is not 0.
  if ($object->depth != 0) {
    return;
  }

  // Add the term to the tree and create a children entry.
  $tree[$object
    ->id()] = $object;
  $tree[$object
    ->id()]->children = [];

  // Reference the tree children to the object children.
  $object_children =& $tree[$object
    ->id()]->children;

  // Load the children of this taxonomy term.
  $children = $this->entityTypeManager
    ->getStorage('taxonomy_term')
    ->loadChildren($object
    ->id());

  // Stop if no children are found.
  if (!$children) {
    return;
  }

  // Iterate through all children and recursively add them to the tree array.
  $child_tree_objects = $this->entityTypeManager
    ->getStorage('taxonomy_term')
    ->loadTree($vocabulary, $object
    ->id(), NULL, TRUE);
  foreach ($children as $child) {
    foreach ($child_tree_objects as $child_tree_object) {
      if ($child_tree_object
        ->id() == $child
        ->id()) {
        $this
          ->buildTree($object_children, $child_tree_object, $vocabulary);
      }
    }
  }
}