You are here

function taxonomy_menu_block_hide_empty in Taxonomy menu block 7

Delete the terms with no nodes attached to them.

Parameters

type $tree:

type $config:

1 call to taxonomy_menu_block_hide_empty()
taxonomy_menu_block_build in ./taxonomy_menu_block.module
Function to build our tree.

File

./taxonomy_menu_block.module, line 583
Taxonomy Menu Block module allows you to make menu blocks out of your taxonomies in a very performant way.

Code

function taxonomy_menu_block_hide_empty($tree, $config) {

  // Get the node count.
  $tids = array_keys($tree);
  $nodes = taxonomy_menu_block_get_nodes($tids, $config['vid'], $config['ctype']);

  // Create helper array with subsequent keys.
  $helper = array();
  foreach ($tree as $tid => $term) {
    $temp = array(
      'tid' => $tid,
      'depth' => $term['depth'],
    );
    $helper[] = $temp;
  }
  $branches = array();
  foreach ($helper as $i => $term) {

    // If the current term has any nodes, set any branches to which this term
    // may belong to to non-delete
    if (isset($nodes[$term['tid']])) {
      foreach ($branches as $b => $branch) {
        $branches[$b]['delete'] = FALSE;
      }
    }

    // Get key for next term.
    $key = $i + 1;

    // If we have only one term or at the end of our array.
    if (!isset($helper[$key])) {
      if (!isset($nodes[$term['tid']])) {
        unset($tree[$term['tid']]);
      }
    }
    else {

      // Get next term.
      $next = $helper[$key];

      // If current and next term have same depth.
      if ($term['depth'] == $next['depth']) {
        if (!isset($nodes[$term['tid']])) {
          unset($tree[$term['tid']]);
        }
      }

      // If next term is higher in depth, we have a new branch.
      if ($term['depth'] < $next['depth']) {

        // If we have no nodes, set parent of branch ready for deletion.
        if (isset($nodes[$term['tid']])) {
          $branches[$term['tid']] = array(
            'tid' => $term['tid'],
            'delete' => FALSE,
          );
        }
        else {
          $branches[$term['tid']] = array(
            'tid' => $term['tid'],
            'delete' => TRUE,
          );
        }
      }

      // If next term is lower in depth, we are at the end of a branch.
      if ($term['depth'] > $next['depth']) {

        // Find out how many branches were closed.
        $depth = $term['depth'] - $next['depth'];
        for ($i = 0; $i < $depth; $i++) {

          // Get last open branch.
          $branch = array_pop($branches);
          if ($branch['delete']) {
            unset($tree[$branch['tid']]);
          }
        }

        // End of branch always means the current term is not a branch itself.
        if (!isset($nodes[$term['tid']])) {
          unset($tree[$term['tid']]);
        }
      }
    }
  }

  // Check remaining branches
  foreach ($branches as $b => $branch) {
    if ($branch['delete']) {
      unset($tree[$branch['tid']]);
    }
  }
  return $tree;
}