Back to Usergroup class

Method rebuild

public bool
rebuild
(mixed $parentId = 0, mixed $left = 0)
Method to recursively rebuild the nested set tree.
Parameters
  • int $parentId The root of the tree to rebuild.
  • int $left The left id to start with in building the tree.
Returns
  • bool True on success
Since
  • 1.7.0
Class: Usergroup
Project: Joomla

Method rebuild - Source code

/**
 * Method to recursively rebuild the nested set tree.
 *
 * @param   integer  $parentId  The root of the tree to rebuild.
 * @param   integer  $left      The left id to start with in building the tree.
 *
 * @return  boolean  True on success
 *
 * @since   1.7.0
 */
public function rebuild($parentId = 0, $left = 0)
{
    // Get the database object
    $db = $this->_db;
    $query = $db->getQuery(true);
    $parentId = (int) $parentId;
    // Get all children of this node
    $query->clear()->select($db->quoteName('id'))->from($db->quoteName($this->_tbl))->where($db->quoteName('parent_id') . ' = :parentid')->bind(':parentid', $parentId, ParameterType::INTEGER)->order([$db->quoteName('parent_id'), $db->quoteName('title')]);
    $db->setQuery($query);
    $children = $db->loadColumn();
    // The right value of this node is the left value + 1
    $right = $left + 1;
    // Execute this function recursively over all children
    for ($i = 0, $n = \count($children); $i < $n; $i++) {
        // $right is the current right value, which is incremented on recursion return
        $right = $this->rebuild($children[$i], $right);
        // If there is an update failure, return false to break out of the recursion
        if ($right === false) {
            return false;
        }
    }
    $left = (int) $left;
    $right = (int) $right;
    // We've got the left value, and now that we've processed
    // the children of this node we also know the right value
    $query->clear()->update($db->quoteName($this->_tbl))->set($db->quoteName('lft') . ' = :lft')->set($db->quoteName('rgt') . ' = :rgt')->where($db->quoteName('id') . ' = :id')->bind(':lft', $left, ParameterType::INTEGER)->bind(':rgt', $right, ParameterType::INTEGER)->bind(':id', $parentId, ParameterType::INTEGER);
    $db->setQuery($query);
    // If there is an update failure, return false to break out of the recursion
    try {
        $db->execute();
    } catch (ExecutionFailureException $e) {
        return false;
    }
    // Return the right value of this node + 1
    return $right + 1;
}