NestedSet.php 32.3 KB
Newer Older
1 2
<?php
/*
3
 *    $Id: NestedSet.php 1382 2007-05-17 19:52:50Z Jonathan.Wage $
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
/**
 * Doctrine_Node_NestedSet
 *
24 25 26 27 28 29 30 31
 * @package    Doctrine
 * @license    http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category   Object Relational Mapping
 * @link       www.phpdoctrine.com
 * @since      1.0
 * @version    $Revision: 1382 $
 * @author     Joe Simms <joe.simms@websites4.com>
 * @author     Roman Borschel <roman@code-factory.org>     
32 33 34
 */
class Doctrine_Node_NestedSet extends Doctrine_Node implements Doctrine_Node_Interface
{
zYne's avatar
zYne committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    /**
     * test if node has previous sibling
     *
     * @return bool            
     */
    public function hasPrevSibling()
    {
        return $this->isValidNode($this->getPrevSibling());        
    }

    /**
     * test if node has next sibling
     *
     * @return bool            
     */ 
    public function hasNextSibling()
    {
        return $this->isValidNode($this->getNextSibling());        
    }

    /**
     * test if node has children
     *
     * @return bool            
     */
    public function hasChildren()
    {
        return (($this->getRightValue() - $this->getLeftValue() ) >1 );        
    }

    /**
     * test if node has parent
     *
     * @return bool            
     */
    public function hasParent()
    {
        return !$this->isRoot();
    }

    /**
     * gets record of prev sibling or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getPrevSibling()
    {
82 83 84 85
        $q = $this->_tree->getBaseQuery();
        $q = $q->where('base.rgt = ?', $this->getLeftValue() - 1);
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
zYne's avatar
zYne committed
86

87 88 89 90 91 92 93 94 95
        if (count($result) <= 0) {
            return false;
        }
        
        if ($result instanceof Doctrine_Collection) {
            $sibling = $result->getFirst();
        } else if (is_array($result)) {
            $sibling = array_shift($result);
        }
zYne's avatar
zYne committed
96
        
97
        return $sibling;
zYne's avatar
zYne committed
98 99 100 101 102 103 104 105 106
    }

    /**
     * gets record of next sibling or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getNextSibling()
    {
107 108 109 110
        $q = $this->_tree->getBaseQuery();
        $q = $q->where('base.lft = ?', $this->getRightValue() + 1);
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
zYne's avatar
zYne committed
111

112 113 114
        if (count($result) <= 0) {
            return false;
        }
zYne's avatar
zYne committed
115
        
116 117 118 119 120 121 122
        if ($result instanceof Doctrine_Collection) {
            $sibling = $result->getFirst();
        } else if (is_array($result)) {
            $sibling = array_shift($result);
        }
        
        return $sibling;
zYne's avatar
zYne committed
123 124 125 126 127 128 129 130 131 132 133
    }

    /**
     * gets siblings for node
     *
     * @return array     array of sibling Doctrine_Record objects            
     */
    public function getSiblings($includeNode = false)
    {
        $parent = $this->getParent();
        $siblings = array();
134 135 136
        if ($parent->exists()) {
            foreach ($parent->getNode()->getChildren() as $child) {
                if ($this->isEqualTo($child) && !$includeNode) {
zYne's avatar
zYne committed
137
                    continue;
138
                }
zYne's avatar
zYne committed
139
                $siblings[] = $child;
140
            }        
zYne's avatar
zYne committed
141 142 143 144 145 146 147 148 149 150 151
        }
        return $siblings;
    }

    /**
     * gets record of first child or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getFirstChild()
    {
152 153 154 155 156 157 158 159
        $q = $this->_tree->getBaseQuery();
        $q->where('base.lft = ?', $this->getLeftValue() + 1);
        $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();

        if (count($result) <= 0) {
            return false;
        }
zYne's avatar
zYne committed
160
        
161 162 163 164 165
        if ($result instanceof Doctrine_Collection) {
            $child = $result->getFirst();
        } else if (is_array($result)) {
            $child = array_shift($result);
        }
zYne's avatar
zYne committed
166
        
167
        return $child;       
zYne's avatar
zYne committed
168 169 170 171 172 173 174 175 176
    }

    /**
     * gets record of last child or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getLastChild()
    {
177 178 179 180
        $q = $this->_tree->getBaseQuery();
        $q->where('base.rgt = ?', $this->getRightValue() - 1);
        $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
zYne's avatar
zYne committed
181

182 183 184
        if (count($result) <= 0) {
            return false;
        }
zYne's avatar
zYne committed
185
        
186 187 188 189 190 191 192
        if ($result instanceof Doctrine_Collection) {
            $child = $result->getFirst();
        } else if (is_array($result)) {
            $child = array_shift($result);
        }
        
        return $child;      
zYne's avatar
zYne committed
193 194 195 196 197
    }

    /**
     * gets children for node (direct descendants only)
     *
198
     * @return mixed The children of the node or FALSE if the node has no children.               
zYne's avatar
zYne committed
199 200 201
     */
    public function getChildren()
    { 
202
        return $this->getDescendants(1);
zYne's avatar
zYne committed
203 204 205 206 207
    }

    /**
     * gets descendants for node (direct descendants only)
     *
208 209 210
     * @return mixed  The descendants of the node or FALSE if the node has no descendants.
     * @todo Currently all descendants are fetched, no matter the depth. Maybe there is a better
     *       solution with less overhead.      
zYne's avatar
zYne committed
211
     */
212
    public function getDescendants($depth = null, $includeNode = false)
zYne's avatar
zYne committed
213
    {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        $q = $this->_tree->getBaseQuery();
        $params = array($this->record->get('lft'), $this->record->get('rgt'));
        
        if ($includeNode) {
            $q->where("base.lft >= ? AND base.rgt <= ?", $params)->orderBy("base.lft asc");
        } else {
            $q->where("base.lft > ? AND base.rgt < ?", $params)->orderBy("base.lft asc");
        }
        
        if ($depth !== null) {
            $q->addWhere("base.level <= ?", $this->record['level'] + $depth);
        }
        
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();

        if (count($result) <= 0) {
            return false;
        }

        return $result;
zYne's avatar
zYne committed
235 236 237 238 239 240 241 242 243
    }

    /**
     * gets record of parent or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getParent()
    {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        $q = $this->_tree->getBaseQuery();
        $q->where("base.lft < ? AND base.rgt > ?", array($this->getLeftValue(), $this->getRightValue()))
                ->orderBy("base.rgt asc");
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
        
        if (count($result) <= 0) {
            return false;
        }
               
        if ($result instanceof Doctrine_Collection) {
            $parent = $result->getFirst();
        } else if (is_array($result)) {
            $parent = array_shift($result);
        }
zYne's avatar
zYne committed
259 260 261 262 263 264 265
        
        return $parent;
    }

    /**
     * gets ancestors for node
     *
266 267 268
     * @param integer $deth  The depth 'upstairs'.
     * @return mixed  The ancestors of the node or FALSE if the node has no ancestors (this 
     *                basically means it's a root node).                
zYne's avatar
zYne committed
269
     */
270
    public function getAncestors($depth = null)
zYne's avatar
zYne committed
271
    {
272 273 274 275 276 277 278 279 280 281 282
        $q = $this->_tree->getBaseQuery();
        $q->where("base.lft < ? AND base.rgt > ?", array($this->getLeftValue(), $this->getRightValue()))
                ->orderBy("base.lft asc");
        if ($depth !== null) {
            $q->addWhere("base.level >= ?", $this->record['level'] - $depth);
        }
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $ancestors = $q->execute();
        if (count($ancestors) <= 0) {
            return false;
        }
zYne's avatar
zYne committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296
        return $ancestors;
    }

    /**
     * gets path to node from root, uses record::toString() method to get node names
     *
     * @param string     $seperator     path seperator
     * @param bool     $includeNode     whether or not to include node at end of path
     * @return string     string representation of path                
     */     
    public function getPath($seperator = ' > ', $includeRecord = false)
    {
        $path = array();
        $ancestors = $this->getAncestors();
297
        foreach ($ancestors as $ancestor) {
zYne's avatar
zYne committed
298 299
            $path[] = $ancestor->__toString();
        }
300
        if ($includeRecord) {
zYne's avatar
zYne committed
301
            $path[] = $this->getRecord()->__toString();
302 303
        }
            
zYne's avatar
zYne committed
304 305 306 307 308 309 310 311 312 313 314 315
        return implode($seperator, $path);
    }

    /**
     * gets number of children (direct descendants)
     *
     * @return int            
     */     
    public function getNumberChildren()
    {
        $count = 0;
        $children = $this->getChildren();
316
        while ($children->next()) {
zYne's avatar
zYne committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
            $count++;
        }
        return $count; 
    }

    /**
     * gets number of descendants (children and their children)
     *
     * @return int            
     */
    public function getNumberDescendants()
    {
        return ($this->getRightValue() - $this->getLeftValue() - 1) / 2;
    }

    /**
     * inserts node as parent of dest record
     *
335 336
     * @return bool
     * @todo Wrap in transaction          
zYne's avatar
zYne committed
337 338 339 340
     */
    public function insertAsParentOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
341
        if ($this->isValidNode()) {
zYne's avatar
zYne committed
342
            return false;
343
        }
zYne's avatar
zYne committed
344
        // cannot insert as parent of root
345
        if ($dest->getNode()->isRoot()) {
zYne's avatar
zYne committed
346
            return false;
347 348 349 350
        }
        $newRoot = $dest->getNode()->getRootValue();
        $this->shiftRLValues($dest->getNode()->getLeftValue(), 1, $newRoot);
        $this->shiftRLValues($dest->getNode()->getRightValue() + 2, 1, $newRoot);
zYne's avatar
zYne committed
351 352
        
        $newLeft = $dest->getNode()->getLeftValue();
353
        $newRight = $dest->getNode()->getRightValue() + 2;
zYne's avatar
zYne committed
354

355
        $this->record['level'] = $dest['level'] - 1;
zYne's avatar
zYne committed
356 357 358 359 360 361 362 363
        $this->insertNode($newLeft, $newRight, $newRoot);
        
        return true;
    }

    /**
     * inserts node as previous sibling of dest record
     *
364 365
     * @return bool
     * @todo Wrap in transaction       
zYne's avatar
zYne committed
366 367 368 369
     */
    public function insertAsPrevSiblingOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
370
        if ($this->isValidNode())
zYne's avatar
zYne committed
371 372 373 374 375 376 377
            return false;

        $newLeft = $dest->getNode()->getLeftValue();
        $newRight = $dest->getNode()->getLeftValue() + 1;
        $newRoot = $dest->getNode()->getRootValue();
        
        $this->shiftRLValues($newLeft, 2, $newRoot);
378
        $this->record['level'] = $dest['level'];
zYne's avatar
zYne committed
379 380 381 382 383 384 385 386 387 388 389
        $this->insertNode($newLeft, $newRight, $newRoot);
        // update destination left/right values to prevent a refresh
        // $dest->getNode()->setLeftValue($dest->getNode()->getLeftValue() + 2);
        // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2);
                        
        return true;
    }

    /**
     * inserts node as next sibling of dest record
     *
390 391
     * @return bool
     * @todo Wrap in transaction           
zYne's avatar
zYne committed
392 393 394 395
     */    
    public function insertAsNextSiblingOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
396
        if ($this->isValidNode())
zYne's avatar
zYne committed
397 398 399 400 401 402 403
            return false;

        $newLeft = $dest->getNode()->getRightValue() + 1;
        $newRight = $dest->getNode()->getRightValue() + 2;
        $newRoot = $dest->getNode()->getRootValue();

        $this->shiftRLValues($newLeft, 2, $newRoot);
404
        $this->record['level'] = $dest['level'];
zYne's avatar
zYne committed
405 406 407 408 409
        $this->insertNode($newLeft, $newRight, $newRoot);

        // update destination left/right values to prevent a refresh
        // no need, node not affected

410
        return true;
zYne's avatar
zYne committed
411 412 413 414 415
    }

    /**
     * inserts node as first child of dest record
     *
416 417
     * @return bool
     * @todo Wrap in transaction         
zYne's avatar
zYne committed
418 419 420 421
     */
    public function insertAsFirstChildOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
422
        if ($this->isValidNode())
zYne's avatar
zYne committed
423 424 425 426 427 428 429
            return false;

        $newLeft = $dest->getNode()->getLeftValue() + 1;
        $newRight = $dest->getNode()->getLeftValue() + 2;
        $newRoot = $dest->getNode()->getRootValue();

        $this->shiftRLValues($newLeft, 2, $newRoot);
430
        $this->record['level'] = $dest['level'] + 1;
zYne's avatar
zYne committed
431 432 433 434 435 436 437 438 439 440 441
        $this->insertNode($newLeft, $newRight, $newRoot);
        
        // update destination left/right values to prevent a refresh
        // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2);

        return true;
    }

    /**
     * inserts node as last child of dest record
     *
442 443
     * @return bool
     * @todo Wrap in transaction            
zYne's avatar
zYne committed
444 445 446 447
     */
    public function insertAsLastChildOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
448
        if ($this->isValidNode())
zYne's avatar
zYne committed
449 450 451 452 453 454 455
            return false;

        $newLeft = $dest->getNode()->getRightValue();
        $newRight = $dest->getNode()->getRightValue() + 1;
        $newRoot = $dest->getNode()->getRootValue();

        $this->shiftRLValues($newLeft, 2, $newRoot);
456
        $this->record['level'] = $dest['level'] + 1;
zYne's avatar
zYne committed
457 458 459 460 461 462 463
        $this->insertNode($newLeft, $newRight, $newRoot);

        // update destination left/right values to prevent a refresh
        // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2);
        
        return true;
    }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    
    /**
     * Accomplishes moving of nodes between different trees.
     * Used by the move* methods if the root value of the two nodes are different.
     *
     * @param Doctrine_Record $dest
     * @param unknown_type $newLeftValue
     * @param unknown_type $moveType
     * @todo Better exception handling/wrapping
     */
    private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveType)
    {
        $conn = $this->record->getTable()->getConnection();
            
            try {
                $conn->beginTransaction();
                
                // Move between trees: Detach from old tree & insert into new tree
                $newRoot = $dest->getNode()->getRootValue();
                $oldRoot = $this->getRootValue();
                $oldLft = $this->getLeftValue();
                $oldRgt = $this->getRightValue();
                $oldLevel = $this->record['level'];
                
                // Prepare target tree for insertion, make room
                $this->shiftRlValues($newLeftValue, $oldRgt - $oldLft - 1, $newRoot);
                
                // Set new root id for this node
                $this->setRootValue($newRoot);
                $this->record->save();
                
                // Close gap in old tree
                $first = $oldRgt + 1;
                $delta = $oldLft - $oldRgt - 1;
                $this->shiftRLValues($first, $delta, $oldRoot);
                
                // Insert this node as a new node
                $this->setRightValue(0);
                $this->setLeftValue(0);
                
                switch ($moveType) {
                    case 'moveAsPrevSiblingOf':
                        $this->insertAsPrevSiblingOf($dest);
                    break;
                    case 'moveAsFirstChildOf':
                        $this->insertAsFirstChildOf($dest);
                    break;
                    case 'moveAsNextSiblingOf':
                        $this->insertAsNextSiblingOf($dest);
                    break;
                    case 'moveAsLastChildOf':
                        $this->insertAsLastChildOf($dest);
                    break;
                    default:
                        throw new Exception("Unknown move operation: $moveType.");
                }
                
                $diff = $oldRgt - $oldLft;
                $this->setRightValue($this->getLeftValue() + ($oldRgt - $oldLft));
                $this->record->save();
                
                $newLevel = $this->record['level'];
                $levelDiff = $newLevel - $oldLevel;
                
                // Relocate descendants of the node
                $diff = $this->getLeftValue() - $oldLft;
                $componentName = $this->record->getTable()->getComponentName();
                $rootColName = $this->record->getTable()->getTree()->getAttribute('rootColumnName');

                // Update lft/rgt/root/level for all descendants
                $q = new Doctrine_Query($conn);
                $q = $q->update($componentName)
                        ->set($componentName . '.lft', 'lft + ' . $diff)
                        ->set($componentName . '.rgt', 'rgt + ' . $diff)
                        ->set($componentName . '.level', 'level + ' . $levelDiff)
                        ->set($componentName . '.' . $rootColName, $newRoot)
                        ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?',
                        array($oldLft, $oldRgt));
                $q = $this->_tree->returnQueryWithRootId($q, $oldRoot);
                $q->execute();
                
                $conn->commit();
            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
    }
    
zYne's avatar
zYne committed
552 553
    /**
     * moves node as prev sibling of dest record
554
     * 
zYne's avatar
zYne committed
555 556 557
     */     
    public function moveAsPrevSiblingOf(Doctrine_Record $dest)
    {
558 559 560 561 562 563 564 565 566
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue(), __FUNCTION__);
        } else {
            // Move within the tree
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'];
            $this->updateNode($dest->getNode()->getLeftValue(), $this->record['level'] - $oldLevel);
        }
zYne's avatar
zYne committed
567 568 569 570 571 572 573 574
    }

    /**
     * moves node as next sibling of dest record
     *        
     */
    public function moveAsNextSiblingOf(Doctrine_Record $dest)
    {
575 576 577 578 579 580 581 582 583
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue() + 1, __FUNCTION__);
        } else {
            // Move within tree
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'];
            $this->updateNode($dest->getNode()->getRightValue() + 1, $this->record['level'] - $oldLevel);
        }
zYne's avatar
zYne committed
584 585 586 587 588 589 590 591
    }

    /**
     * moves node as first child of dest record
     *            
     */
    public function moveAsFirstChildOf(Doctrine_Record $dest)
    {
592 593 594 595 596 597 598 599 600
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue() + 1, __FUNCTION__);
        } else {
            // Move within tree
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'] + 1;
            $this->updateNode($dest->getNode()->getLeftValue() + 1, $this->record['level'] - $oldLevel);
        }
zYne's avatar
zYne committed
601 602 603 604 605 606 607 608
    }

    /**
     * moves node as last child of dest record
     *        
     */
    public function moveAsLastChildOf(Doctrine_Record $dest)
    {
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue(), __FUNCTION__);
        } else {
            // Move within tree
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'] + 1;
            $this->updateNode($dest->getNode()->getRightValue(), $this->record['level'] - $oldLevel);
        }
    }
    
    /**
     * Makes this node a root node. Only used in multiple-root trees.
     *
     * @todo Exception handling/wrapping
     */
    public function makeRoot($newRootId)
    {
        // TODO: throw exception instead?
        if ($this->getLeftValue() == 1 || !$this->record->getTable()->getTree()->getAttribute('hasManyRoots')) {
            return false;
        }
        
        $oldRgt = $this->getRightValue();
        $oldLft = $this->getLeftValue();
        $oldRoot = $this->getRootValue();
        $oldLevel = $this->record['level'];
        
        try {
            $conn = $this->record->getTable()->getConnection();
            $conn->beginTransaction();
            
            // Detach from old tree (close gap in old tree)
            $first = $oldRgt + 1;
            $delta = $oldLft - $oldRgt - 1;
            $this->shiftRLValues($first, $delta, $this->getRootValue());
            
            // Set new lft/rgt/root/level values for root node
            $this->setLeftValue(1);
            $this->setRightValue($oldRgt - $oldLft + 1);
            $this->setRootValue($newRootId);
            $this->record['level'] = 0;
            
            // Update descendants lft/rgt/root/level values
            $diff = 1 - $oldLft;
            $newRoot = $newRootId;
            $componentName = $this->record->getTable()->getComponentName();
            $rootColName = $this->record->getTable()->getTree()->getAttribute('rootColumnName');
            $q = new Doctrine_Query($conn);
            $q = $q->update($componentName)
                    ->set($componentName . '.lft', 'lft + ' . $diff)
                    ->set($componentName . '.rgt', 'rgt + ' . $diff)
                    ->set($componentName . '.level', 'level - ' . $oldLevel)
                    ->set($componentName . '.' . $rootColName, $newRoot)
                    ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?',
                    array($oldLft, $oldRgt));
            $q = $this->_tree->returnQueryWithRootId($q, $oldRoot);
            $q->execute();
            
            $conn->commit();
            
        } catch (Exception $e) {
            $conn->rollback();
            throw $e;
        }
zYne's avatar
zYne committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
    }

    /**
     * adds node as last child of record
     *        
     */
    public function addChild(Doctrine_Record $record)
    {
        $record->getNode()->insertAsLastChildOf($this->getRecord());
    }

    /**
     * determines if node is leaf
     *
     * @return bool            
     */
    public function isLeaf()
    {
692
        return (($this->getRightValue() - $this->getLeftValue()) == 1);
zYne's avatar
zYne committed
693 694 695 696 697 698 699 700 701
    }

    /**
     * determines if node is root
     *
     * @return bool            
     */
    public function isRoot()
    {
702
        return ($this->getLeftValue() == 1);
zYne's avatar
zYne committed
703 704 705 706 707 708 709 710 711
    }

    /**
     * determines if node is equal to subject node
     *
     * @return bool            
     */    
    public function isEqualTo(Doctrine_Record $subj)
    {
712 713 714 715
        return (($this->getLeftValue() == $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() == $subj->getNode()->getRightValue()) && 
                ($this->getRootValue() == $subj->getNode()->getRootValue())
                );
zYne's avatar
zYne committed
716 717 718 719 720
    }

    /**
     * determines if node is child of subject node
     *
721
     * @return bool
zYne's avatar
zYne committed
722 723 724
     */
    public function isDescendantOf(Doctrine_Record $subj)
    {
725 726 727
        return (($this->getLeftValue() > $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() < $subj->getNode()->getRightValue()) &&
                ($this->getRootValue() == $subj->getNode()->getRootValue()));
zYne's avatar
zYne committed
728 729 730 731 732 733 734 735 736
    }

    /**
     * determines if node is child of or sibling to subject node
     *
     * @return bool            
     */
    public function isDescendantOfOrEqualTo(Doctrine_Record $subj)
    {
737 738 739
        return (($this->getLeftValue() >= $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() <= $subj->getNode()->getRightValue()) &&
                ($this->getRootValue() == $subj->getNode()->getRootValue()));
zYne's avatar
zYne committed
740 741 742 743 744 745 746
    }

    /**
     * determines if node is valid
     *
     * @return bool            
     */
747
    public function isValidNode(Doctrine_Record $record = null)
zYne's avatar
zYne committed
748
    {
749 750 751 752 753
        if ($record === null) {
          return ($this->getRightValue() > $this->getLeftValue());
        } else {
          return ($record->getNode()->getRightValue() > $record->getNode()->getLeftValue());
        }
zYne's avatar
zYne committed
754 755 756 757
    }

    /**
     * deletes node and it's descendants
758
     * @todo Delete more efficiently. Wrap in transaction if needed.      
zYne's avatar
zYne committed
759 760 761 762
     */
    public function delete()
    {
        // TODO: add the setting whether or not to delete descendants or relocate children
763 764
        $oldRoot = $this->getRootValue();
        $q = $this->_tree->getBaseQuery();
zYne's avatar
zYne committed
765 766 767
        
        $componentName = $this->record->getTable()->getComponentName();

768
        $q = $q->where('base.lft >= ? AND base.rgt <= ?', array($this->getLeftValue(), $this->getRightValue()));
zYne's avatar
zYne committed
769

770
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $oldRoot);
zYne's avatar
zYne committed
771 772 773 774 775 776 777
        
        $coll = $q->execute();

        $coll->delete();

        $first = $this->getRightValue() + 1;
        $delta = $this->getLeftValue() - $this->getRightValue() - 1;
778
        $this->shiftRLValues($first, $delta, $oldRoot);
zYne's avatar
zYne committed
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
        
        return true; 
    }

    /**
     * sets node's left and right values and save's it
     *
     * @param int     $destLeft     node left value
     * @param int        $destRight    node right value
     */    
    private function insertNode($destLeft = 0, $destRight = 0, $destRoot = 1)
    {
        $this->setLeftValue($destLeft);
        $this->setRightValue($destRight);
        $this->setRootValue($destRoot);
        $this->record->save();    
    }

    /**
     * move node's and its children to location $destLeft and updates rest of tree
     *
     * @param int     $destLeft    destination left value
801
     * @todo Wrap in transaction
zYne's avatar
zYne committed
802
     */
803
    private function updateNode($destLeft, $levelDiff)
zYne's avatar
zYne committed
804
    { 
805
        $componentName = $this->record->getTable()->getComponentName();
zYne's avatar
zYne committed
806 807
        $left = $this->getLeftValue();
        $right = $this->getRightValue();
808
        $rootId = $this->getRootValue();
zYne's avatar
zYne committed
809 810 811

        $treeSize = $right - $left + 1;

812 813
        // Make room in the new tree
        $this->shiftRLValues($destLeft, $treeSize, $rootId);
zYne's avatar
zYne committed
814

815
        if ($left >= $destLeft){ // src was shifted too?
zYne's avatar
zYne committed
816 817 818 819
            $left += $treeSize;
            $right += $treeSize;
        }

820 821 822 823 824 825 826 827 828
        // update level for descendants
        $q = new Doctrine_Query();
        $q = $q->update($componentName)
                ->set($componentName . '.level', 'level + ' . $levelDiff)
                ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?',
                        array($left, $right));
        $q = $this->_tree->returnQueryWithRootId($q, $rootId);
        $q->execute();
        
zYne's avatar
zYne committed
829
        // now there's enough room next to target to move the subtree
830
        $this->shiftRLRange($left, $right, $destLeft - $left, $rootId);
zYne's avatar
zYne committed
831

832 833
        // correct values after source (close gap in old tree)
        $this->shiftRLValues($right + 1, -$treeSize, $rootId);
zYne's avatar
zYne committed
834 835 836 837 838 839 840 841 842 843 844

        $this->record->save();
        $this->record->refresh();
    }

    /**
     * adds '$delta' to all Left and Right values that are >= '$first'. '$delta' can also be negative.
     *
     * @param int $first         First node to be shifted
     * @param int $delta         Value to be shifted by, can be negative
     */    
845
    private function shiftRlValues($first, $delta, $rootId = 1)
zYne's avatar
zYne committed
846
    {
847 848
        $qLeft  = new Doctrine_Query();
        $qRight = new Doctrine_Query();
zYne's avatar
zYne committed
849 850

        // shift left columns
851 852 853 854
        $componentName = $this->record->getTable()->getComponentName();
        $qLeft = $qLeft->update($componentName)
                                ->set($componentName . '.lft', 'lft + ' . $delta)
                                ->where($componentName . '.lft >= ?', $first);
zYne's avatar
zYne committed
855

856
        $qLeft = $this->record->getTable()->getTree()->returnQueryWithRootId($qLeft, $rootId);
zYne's avatar
zYne committed
857 858 859 860
        
        $resultLeft = $qLeft->execute();
        
        // shift right columns
861 862 863
        $resultRight = $qRight->update($componentName)
                                ->set($componentName . '.rgt', 'rgt + ' . $delta)
                                ->where($componentName . '.rgt >= ?', $first);
zYne's avatar
zYne committed
864

865
        $qRight = $this->record->getTable()->getTree()->returnQueryWithRootId($qRight, $rootId);
zYne's avatar
zYne committed
866 867 868 869 870 871 872 873 874 875 876 877

        $resultRight = $qRight->execute();
    }

    /**
     * adds '$delta' to all Left and Right values that are >= '$first' and <= '$last'. 
     * '$delta' can also be negative.
     *
     * @param int $first     First node to be shifted (L value)
     * @param int $last     Last node to be shifted (L value)
     * @param int $delta         Value to be shifted by, can be negative
     */ 
878
    private function shiftRlRange($first, $last, $delta, $rootId = 1)
zYne's avatar
zYne committed
879
    {
880 881
        $qLeft  = new Doctrine_Query();
        $qRight = new Doctrine_Query();
zYne's avatar
zYne committed
882 883

        // shift left column values
884 885 886 887
        $componentName = $this->record->getTable()->getComponentName();
        $qLeft = $qLeft->update($componentName)
                                ->set($componentName . '.lft', 'lft + ' . $delta)
                                ->where($componentName . '.lft >= ? AND ' . $componentName . '.lft <= ?', array($first, $last));
zYne's avatar
zYne committed
888
        
889
        $qLeft = $this->record->getTable()->getTree()->returnQueryWithRootId($qLeft, $rootId);
zYne's avatar
zYne committed
890 891 892 893

        $resultLeft = $qLeft->execute();
        
        // shift right column values
894 895 896
        $qRight = $qRight->update($componentName)
                                ->set($componentName . '.rgt', 'rgt + ' . $delta)
                                ->where($componentName . '.rgt >= ? AND ' . $componentName . '.rgt <= ?', array($first, $last));
zYne's avatar
zYne committed
897

898
        $qRight = $this->record->getTable()->getTree()->returnQueryWithRootId($qRight, $rootId);
zYne's avatar
zYne committed
899 900 901

        $resultRight = $qRight->execute();
    }
902
    
zYne's avatar
zYne committed
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    /**
     * gets record's left value
     *
     * @return int            
     */     
    public function getLeftValue()
    {
        return $this->record->get('lft');
    }

    /**
     * sets record's left value
     *
     * @param int            
     */     
    public function setLeftValue($lft)
    {
        $this->record->set('lft', $lft);        
    }

    /**
     * gets record's right value
     *
     * @return int            
     */     
    public function getRightValue()
    {
        return $this->record->get('rgt');        
    }

    /**
     * sets record's right value
     *
     * @param int            
     */    
    public function setRightValue($rgt)
    {
        $this->record->set('rgt', $rgt);         
    }

    /**
     * gets level (depth) of node in the tree
     *
     * @return int            
     */    
    public function getLevel()
    {
950 951 952 953
        if (!isset($this->level)) {
            $componentName = $this->record->getTable()->getComponentName();
            $q = $this->_tree->getBaseQuery();
            $q = $q->where('base.lft < ? AND base.rgt > ?', array($this->getLeftValue(), $this->getRightValue()));
zYne's avatar
zYne committed
954

955
            $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
956
            
zYne's avatar
zYne committed
957
            $coll = $q->execute();
958

959
            $this->level = count($coll) ? count($coll) : 0;
zYne's avatar
zYne committed
960 961 962
        }
        return $this->level;
    }
963

zYne's avatar
zYne committed
964 965 966 967 968 969 970 971 972
    /**
     * sets node's level
     *
     * @param int            
     */    
    public function setLevel($level)
    {
        $this->level = $level;         
    }
973

zYne's avatar
zYne committed
974 975 976 977 978 979
    /**
     * get records root id value
     *            
     */     
    public function getRootValue()
    {
980 981 982
        if ($this->_tree->getAttribute('hasManyRoots')) {
            return $this->record->get($this->_tree->getAttribute('rootColumnName'));
        }
zYne's avatar
zYne committed
983 984 985 986 987 988 989 990 991 992
        return 1;
    }

    /**
     * sets records root id value
     *
     * @param int            
     */
    public function setRootValue($value)
    {
993 994 995
        if ($this->_tree->getAttribute('hasManyRoots')) {
            $this->record->set($this->_tree->getAttribute('rootColumnName'), $value);   
        }    
zYne's avatar
zYne committed
996 997
    }
}