NestedSet.php 21.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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
<?php
/*
 *    $Id$
 *
 * 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
 *
 * @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$
 * @author            Joe Simms <joe.simms@websites4.com>
 */
class Doctrine_Node_NestedSet extends Doctrine_Node implements Doctrine_Node_Interface
{
    /**
     * 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()
    {
        $q = $this->record->getTable()->createQuery();
82 83 84
        $q = $q->where('rgt = ?', $this->getLeftValue() - 1);
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute()->getFirst();
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

        if(!$result)
             $result = $this->record->getTable()->create();
        
        return $result;    
    }

    /**
     * gets record of next sibling or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getNextSibling()
    {
        $q = $this->record->getTable()->createQuery();
100 101 102
        $q = $q->where('lft = ?', $this->getRightValue() + 1);
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute()->getFirst();
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

        if(!$result)
             $result = $this->record->getTable()->create();
        
        return $result;
    }

    /**
     * gets siblings for node
     *
     * @return array     array of sibling Doctrine_Record objects            
     */
    public function getSiblings($includeNode = false)
    {
        $parent = $this->getParent();
        $siblings = array();
        if($parent->exists())
        {
            foreach($parent->getNode()->getChildren() as $child)
            {
                if($this->isEqualTo($child) && !$includeNode)
                    continue;
                    
                $siblings[] = $child;
            }            
        }
    
        return $siblings;
    }

    /**
     * gets record of first child or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getFirstChild()
    {
        $q = $this->record->getTable()->createQuery();
141 142 143
        $q = $q->where('lft = ?', $this->getLeftValue() + 1);
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute()->getFirst();
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        
        if(!$result)
             $result = $this->record->getTable()->create();
        
        return $result;        
    }

    /**
     * gets record of last child or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getLastChild()
    {
        $q = $this->record->getTable()->createQuery();
159 160 161
        $q = $q->where('rgt = ?', $this->getRightValue() - 1);
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute()->getFirst();
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

        if(!$result)
             $result = $this->record->getTable()->create();
        
        return $result;     
    }

    /**
     * gets children for node (direct descendants only)
     *
     * @return array     array of sibling Doctrine_Record objects                
     */
    public function getChildren()
    { 
        return $this->getIterator('Pre', array('depth' => 1));
    }

    /**
     * gets descendants for node (direct descendants only)
     *
     * @return iterator     iterator to traverse descendants from node                
     */
    public function getDescendants()
    {
        return $this->getIterator();
    }

    /**
     * gets record of parent or empty record
     *
     * @return object     Doctrine_Record            
     */
    public function getParent()
    {
        $q = $this->record->getTable()->createQuery();

198
        $componentName = $this->record->getTable()->getComponentName();
199 200 201 202 203 204
        $q = $q->where("$componentName.lft < ? AND $componentName.rgt > ?", array($this->getLeftValue(), $this->getRightValue()))
                                    ->orderBy("$componentName.rgt asc");
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
                                         
        $parent =  $q->execute()->getFirst();
        
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

        if(!$parent)
             $parent = $this->record->getTable()->create();
        
        return $parent;
    }

    /**
     * gets ancestors for node
     *
     * @return object     Doctrine_Collection                
     */
    public function getAncestors()
    {
        $q = $this->record->getTable()->createQuery();

221
        $componentName = $this->record->getTable()->getComponentName();
222 223 224 225 226
        $q = $q->where("$componentName.lft < ? AND $componentName.rgt > ?", array($this->getLeftValue(), $this->getRightValue()))
                                        ->orderBy("$componentName.lft asc");
        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
        $ancestors = $q->execute();
        
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 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();
        foreach($ancestors as $ancestor)
        {
            $path[] = $ancestor->__toString();
        }
        if($includeRecord)
            $path[] = $this->getRecord()->__toString();
        
        return implode($seperator, $path);
    }

    /**
     * gets number of children (direct descendants)
     *
     * @return int            
     */     
    public function getNumberChildren()
    {
        $count = 0;
        $children = $this->getChildren();
    
        while($children->next())
        {
            $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
     *
     * @return bool            
     */
    public function insertAsParentOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
        if($this->isValidNode())
            return false;
        
        // cannot insert as parent of root
        if($dest->getNode()->isRoot())
            return false;

        $this->shiftRLValues($dest->getNode()->getLeftValue(), 1);
        $this->shiftRLValues($dest->getNode()->getRightValue() + 2, 1);
        
        $newLeft = $dest->getNode()->getLeftValue();
zYne's avatar
zYne committed
297
        $newRight = $dest->getNode()->getRightValue() + 2;
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        $newRoot = $dest->getNode()->getRootValue();

        $this->insertNode($newLeft, $newRight, $newRoot);
        
        return true;
    }

    /**
     * inserts node as previous sibling of dest record
     *
     * @return bool            
     */
    public function insertAsPrevSiblingOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
        if($this->isValidNode())
            return false;

        $newLeft = $dest->getNode()->getLeftValue();
        $newRight = $dest->getNode()->getLeftValue() + 1;
        $newRoot = $dest->getNode()->getRootValue();
        
        $this->shiftRLValues($newLeft, 2, $newRoot);
        $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
     *
     * @return bool            
     */    
    public function insertAsNextSiblingOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
        if($this->isValidNode())
            return false;

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

        $this->shiftRLValues($newLeft, 2, $newRoot);
        $this->insertNode($newLeft, $newRight, $newRoot);

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

        return true;    
    }

    /**
     * inserts node as first child of dest record
     *
     * @return bool            
     */
    public function insertAsFirstChildOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
        if($this->isValidNode())
            return false;

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

        $this->shiftRLValues($newLeft, 2, $newRoot);
        $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
     *
     * @return bool            
     */
    public function insertAsLastChildOf(Doctrine_Record $dest)
    {
        // cannot insert a node that has already has a place within the tree
        if($this->isValidNode())
            return false;

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

        $this->shiftRLValues($newLeft, 2, $newRoot);
        $this->insertNode($newLeft, $newRight, $newRoot);

        // update destination left/right values to prevent a refresh
        // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2);
        
        return true;
    }

    /**
     * moves node as prev sibling of dest record
     *        
     */     
    public function moveAsPrevSiblingOf(Doctrine_Record $dest)
    {
        $this->updateNode($dest->getNode()->getLeftValue());
    }

    /**
     * moves node as next sibling of dest record
     *        
     */
    public function moveAsNextSiblingOf(Doctrine_Record $dest)
    {
        $this->updateNode($dest->getNode()->getRightValue() + 1);
    }

    /**
     * moves node as first child of dest record
     *            
     */
    public function moveAsFirstChildOf(Doctrine_Record $dest)
    {
        $this->updateNode($dest->getNode()->getLeftValue() + 1);
    }

    /**
     * moves node as last child of dest record
     *        
     */
    public function moveAsLastChildOf(Doctrine_Record $dest)
    {
        $this->updateNode($dest->getNode()->getRightValue());
    }

    /**
     * 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()
    {
zYne's avatar
zYne committed
453
        return (($this->getRightValue() - $this->getLeftValue()) == 1);
454 455 456 457 458 459 460 461 462
    }

    /**
     * determines if node is root
     *
     * @return bool            
     */
    public function isRoot()
    {
zYne's avatar
zYne committed
463
        return ($this->getLeftValue() == 1);
464 465 466 467 468 469 470 471 472
    }

    /**
     * determines if node is equal to subject node
     *
     * @return bool            
     */    
    public function isEqualTo(Doctrine_Record $subj)
    {
zYne's avatar
zYne committed
473 474 475 476
        return (($this->getLeftValue() == $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() == $subj->getNode()->getRightValue()) && 
                ($this->getRootValue() == $subj->getNode()->getRootValue())
                );
477 478 479 480 481
    }

    /**
     * determines if node is child of subject node
     *
zYne's avatar
zYne committed
482
     * @return bool
483 484 485
     */
    public function isDescendantOf(Doctrine_Record $subj)
    {
zYne's avatar
zYne committed
486
        return (($this->getLeftValue()>$subj->getNode()->getLeftValue()) && ($this->getRightValue()<$subj->getNode()->getRightValue()) && ($this->getRootValue() == $subj->getNode()->getRootValue()));
487 488 489 490 491 492 493 494 495
    }

    /**
     * determines if node is child of or sibling to subject node
     *
     * @return bool            
     */
    public function isDescendantOfOrEqualTo(Doctrine_Record $subj)
    {
zYne's avatar
zYne committed
496
        return (($this->getLeftValue()>=$subj->getNode()->getLeftValue()) && ($this->getRightValue()<=$subj->getNode()->getRightValue()) && ($this->getRootValue() == $subj->getNode()->getRootValue()));
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    }

    /**
     * determines if node is valid
     *
     * @return bool            
     */
    public function isValidNode()
    {
        return ($this->getRightValue() > $this->getLeftValue());
    }

    /**
     * deletes node and it's descendants
     *            
     */
    public function delete()
    {
        // TODO: add the setting whether or not to delete descendants or relocate children

        $q = $this->record->getTable()->createQuery();
        
        $componentName = $this->record->getTable()->getComponentName();

zYne's avatar
zYne committed
521
        $q = $q->where($componentName. '.lft >= ? AND ' . $componentName . '.rgt <= ?', array($this->getLeftValue(), $this->getRightValue()));
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 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

        $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
        
        $coll = $q->execute();

        $coll->delete();

        $first = $this->getRightValue() + 1;
        $delta = $this->getLeftValue() - $this->getRightValue() - 1;
        $this->shiftRLValues($first, $delta);
        
        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
     */
    private function updateNode($destLeft)
    { 
        $left = $this->getLeftValue();
        $right = $this->getRightValue();

        $treeSize = $right - $left + 1;

        $this->shiftRLValues($destLeft, $treeSize);

        if($left >= $destLeft){ // src was shifted too?
            $left += $treeSize;
            $right += $treeSize;
        }

        // now there's enough room next to target to move the subtree
        $this->shiftRLRange($left, $right, $destLeft - $left);

        // correct values after source
        $this->shiftRLValues($right + 1, -$treeSize);

        $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
     */    
zYne's avatar
zYne committed
585
    private function shiftRlValues($first, $delta, $rootId = 1)
586
    {
zYne's avatar
zYne committed
587 588
        $qLeft  = new Doctrine_Query();
        $qRight = new Doctrine_Query();
589 590 591 592 593

        // TODO: Wrap in transaction

        // shift left columns
        $qLeft = $qLeft->update($this->record->getTable()->getComponentName())
zYne's avatar
zYne committed
594
                                ->set('lft', 'lft + ' . $delta)
595 596
                                ->where('lft >= ?', $first);

zYne's avatar
zYne committed
597
        $qLeft = $this->record->getTable()->getTree()->returnQueryWithRootId($qLeft, $rootId);
598 599 600 601 602
        
        $resultLeft = $qLeft->execute();
        
        // shift right columns
        $resultRight = $qRight->update($this->record->getTable()->getComponentName())
zYne's avatar
zYne committed
603
                                ->set('rgt', 'rgt + ' . $delta)
604 605
                                ->where('rgt >= ?', $first);

zYne's avatar
zYne committed
606
        $qRight = $this->record->getTable()->getTree()->returnQueryWithRootId($qRight, $rootId);
607 608 609 610 611 612 613 614 615 616 617 618

        $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
     */ 
zYne's avatar
zYne committed
619
    private function shiftRlRange($first, $last, $delta, $rootId = 1)
620
    {
zYne's avatar
zYne committed
621 622
        $qLeft  = new Doctrine_Query();
        $qRight = new Doctrine_Query();
623 624 625 626 627
        
        // TODO : Wrap in transaction

        // shift left column values
        $qLeft = $qLeft->update($this->record->getTable()->getComponentName())
zYne's avatar
zYne committed
628
                                ->set('lft', 'lft + ' . $delta)
629 630
                                ->where('lft >= ? AND lft <= ?', array($first, $last));
        
zYne's avatar
zYne committed
631
        $qLeft = $this->record->getTable()->getTree()->returnQueryWithRootId($qLeft, $rootId);
632 633 634 635 636

        $resultLeft = $qLeft->execute();
        
        // shift right column values
        $qRight = $qRight->update($this->record->getTable()->getComponentName())
zYne's avatar
zYne committed
637
                                ->set('rgt', 'rgt + ' . $delta)
638 639
                                ->where('rgt >= ? AND rgt <= ?', array($first, $last));

zYne's avatar
zYne committed
640
        $qRight = $this->record->getTable()->getTree()->returnQueryWithRootId($qRight, $rootId);
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 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

        $resultRight = $qRight->execute();
    }
    
    /**
     * 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()
    {
        if(!isset($this->level))
        {
            $q = $this->record->getTable()->createQuery();
            $q = $q->where('lft < ? AND rgt > ?', array($this->getLeftValue(), $this->getRightValue()));

            $q = $this->record->getTable()->getTree()->returnQueryWithRootId($q, $this->getRootValue());
            
            $coll = $q->execute();

            $this->level = $coll->count() ? $coll->count() : 0;
        }

        return $this->level;
    }

    /**
     * sets node's level
     *
     * @param int            
     */    
    public function setLevel($level)
    {
        $this->level = $level;         
    }

    /**
     * get records root id value
     *            
     */     
    public function getRootValue()
    {
723 724
        if($this->record->getTable()->getTree()->getAttribute('hasManyRoots'))
            return $this->record->get($this->record->getTable()->getTree()->getAttribute('rootColumnName'));
725 726 727 728 729 730 731 732 733 734 735
        
        return 1;
    }

    /**
     * sets records root id value
     *
     * @param int            
     */
    public function setRootValue($value)
    {
736 737
        if($this->record->getTable()->getTree()->getAttribute('hasManyRoots'))
            $this->record->set($this->record->getTable()->getTree()->getAttribute('rootColumnName'), $value);     
738 739
    }
}