You are here

function _taxonomy_manager_tree_get_first_path in Taxonomy Manager 7

Same name and namespace in other branches
  1. 6.2 taxonomy_manager.module \_taxonomy_manager_tree_get_first_path()

calculates a path to a certain term and merges it into the tree

1 call to _taxonomy_manager_tree_get_first_path()
taxonomy_manager_tree_process_elements in ./taxonomy_manager.module
Processes the tree form element

File

./taxonomy_manager.module, line 458
Taxonomy Manager

Code

function _taxonomy_manager_tree_get_first_path($tid, &$tree, &$terms_to_expand) {
  $path = array();
  $next_tid = $tid;
  $i = 0;
  while ($i < 100) {

    //prevent infinite loop if inconsistent hierarchy
    $parents = taxonomy_get_parents($next_tid);
    if (count($parents)) {

      // Takes first parent.
      $parent = array_shift($parents);
      $path[] = $parent;
      $next_tid = $parent->tid;
      if (taxonomy_manager_term_is_root($next_tid)) {
        break;
      }
    }
    else {
      break;
    }
    $i++;
  }
  $path = array_reverse($path);
  $path[] = taxonomy_term_load($tid);
  $root_term = $path[0];
  $root_term_index;

  // build a map of the path keyed on tid - helps in avoiding duplicates when merging multiple paths to the tree
  $term_map = array();
  if (count($path) > 1) {
    foreach ($tree as $index => $term) {
      $term_map[$term->tid] = $index;
      if ($term->tid == $root_term->tid) {
        $root_term_index = $index;
      }
    }
    reset($tree);
  }
  if (isset($root_term_index)) {
    $path_tree = taxonomy_manager_get_partial_tree($path);

    // build map of path tree keyed on tids
    $path_term_map = array();
    foreach ($path_tree as $index => $term) {
      $path_term_map[$term->tid] = $index;
    }
    reset($path_tree);

    // first find the set of new terms that we need to add - new terms should be contiguous within $path_tree
    $new_path_terms_map = array_diff_key($path_term_map, $term_map);
    if (!empty($new_path_terms_map)) {

      // something to add
      $insert_term_index = reset($new_path_terms_map);
      if ($insert_term_index > 0) {

        // use previous term as insertion point
        $previous_tid = $path_tree[$insert_term_index - 1]->tid;
        $insertion_index = $term_map[$previous_tid];
      }
      else {

        // use root index as insertion point
        $insertion_index = $root_term_index;
      }

      // get the new terms to add from the path tree
      $new_path_tree = array_slice($path_tree, $insert_term_index, count($new_path_terms_map));

      // stick the new terms into the tree at the insertion point
      array_splice($tree, $insertion_index + 1, 0, $new_path_tree);
    }
  }
}