NestedSet.php 33 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?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
19
 * <http://www.phpdoctrine.org>.
20
 */
21

22 23 24
/**
 * Doctrine_Node_NestedSet
 *
25
 * @package    Doctrine
26
 * @subpackage Node
27
 * @license    http://www.opensource.org/licenses/lgpl-license.php LGPL
28
 * @link       www.phpdoctrine.org
29 30 31 32
 * @since      1.0
 * @version    $Revision$
 * @author     Joe Simms <joe.simms@websites4.com>
 * @author     Roman Borschel <roman@code-factory.org>     
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
 */
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()
    {
romanb's avatar
romanb committed
63
        return (($this->getRightValue() - $this->getLeftValue()) > 1);        
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    }

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

    /**
     * gets record of prev sibling or empty record
     *
79
     * @return object     Doctrine_Entity            
80 81 82
     */
    public function getPrevSibling()
    {
83
        $baseAlias = $this->_tree->getBaseAlias();
84
        $q = $this->_tree->getBaseQuery();
85
        $q = $q->addWhere("$baseAlias.rgt = ?", $this->getLeftValue() - 1);
86 87
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
88

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

    /**
     * gets record of next sibling or empty record
     *
105
     * @return object     Doctrine_Entity            
106 107 108
     */
    public function getNextSibling()
    {
109
        $baseAlias = $this->_tree->getBaseAlias();
110
        $q = $this->_tree->getBaseQuery();
111
        $q = $q->addWhere("$baseAlias.lft = ?", $this->getRightValue() + 1);
112 113
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
114

115 116 117
        if (count($result) <= 0) {
            return false;
        }
118
        
119 120 121 122 123 124 125
        if ($result instanceof Doctrine_Collection) {
            $sibling = $result->getFirst();
        } else if (is_array($result)) {
            $sibling = array_shift($result);
        }
        
        return $sibling;
126 127 128 129 130
    }

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

    /**
     * gets record of first child or empty record
     *
151
     * @return object     Doctrine_Entity            
152 153 154
     */
    public function getFirstChild()
    {
155
        $baseAlias = $this->_tree->getBaseAlias();
156
        $q = $this->_tree->getBaseQuery();
157
        $q->addWhere("$baseAlias.lft = ?", $this->getLeftValue() + 1);
158 159 160 161 162 163
        $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();

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

    /**
     * gets record of last child or empty record
     *
177
     * @return object     Doctrine_Entity            
178 179 180
     */
    public function getLastChild()
    {
181
        $baseAlias = $this->_tree->getBaseAlias();
182
        $q = $this->_tree->getBaseQuery();
183
        $q->addWhere("$baseAlias.rgt = ?", $this->getRightValue() - 1);
184 185
        $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
186

187 188 189 190 191 192 193 194 195
        if (count($result) <= 0) {
            return false;
        }
        
        if ($result instanceof Doctrine_Collection) {
            $child = $result->getFirst();
        } else if (is_array($result)) {
            $child = array_shift($result);
        }
196
        
197
        return $child;      
198 199 200 201 202
    }

    /**
     * gets children for node (direct descendants only)
     *
203
     * @return mixed The children of the node or FALSE if the node has no children.               
204 205 206
     */
    public function getChildren()
    { 
207
        return $this->getDescendants(1);
208 209 210 211 212
    }

    /**
     * gets descendants for node (direct descendants only)
     *
213 214 215
     * @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.      
216
     */
217
    public function getDescendants($depth = null, $includeNode = false)
218
    {
219
        $baseAlias = $this->_tree->getBaseAlias();
220 221 222 223
        $q = $this->_tree->getBaseQuery();
        $params = array($this->record->get('lft'), $this->record->get('rgt'));
        
        if ($includeNode) {
224
            $q->addWhere("$baseAlias.lft >= ? AND $baseAlias.rgt <= ?", $params)->addOrderBy("$baseAlias.lft asc");
225
        } else {
226
            $q->addWhere("$baseAlias.lft > ? AND $baseAlias.rgt < ?", $params)->addOrderBy("$baseAlias.lft asc");
227 228 229
        }
        
        if ($depth !== null) {
230
            $q->addWhere("$baseAlias.level <= ?", $this->record['level'] + $depth);
231 232 233 234 235 236 237 238 239 240
        }
        
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();

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

        return $result;
241 242 243 244 245
    }

    /**
     * gets record of parent or empty record
     *
246
     * @return object     Doctrine_Entity            
247 248 249
     */
    public function getParent()
    {
250
        $baseAlias = $this->_tree->getBaseAlias();
251
        $q = $this->_tree->getBaseQuery();
252 253
        $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue()))
                ->addOrderBy("$baseAlias.rgt asc");
254 255
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
        $result = $q->execute();
256
        
257 258 259 260 261 262 263 264 265
        if (count($result) <= 0) {
            return false;
        }
               
        if ($result instanceof Doctrine_Collection) {
            $parent = $result->getFirst();
        } else if (is_array($result)) {
            $parent = array_shift($result);
        }
266 267 268 269 270 271 272
        
        return $parent;
    }

    /**
     * gets ancestors for node
     *
273 274 275
     * @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).                
276
     */
277
    public function getAncestors($depth = null)
278
    {
279
        $baseAlias = $this->_tree->getBaseAlias();
280
        $q = $this->_tree->getBaseQuery();
281 282
        $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue()))
                ->addOrderBy("$baseAlias.lft asc");
283
        if ($depth !== null) {
284
            $q->addWhere("$baseAlias.level >= ?", $this->record['level'] - $depth);
285 286
        }
        $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
287
        $ancestors = $q->execute();
288 289 290
        if (count($ancestors) <= 0) {
            return false;
        }
291 292 293 294 295 296 297 298 299 300 301 302 303 304
        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();
305 306 307 308
        if ($ancestors) {
            foreach ($ancestors as $ancestor) {
                $path[] = $ancestor->__toString();
            }
309
        }
310
        if ($includeRecord) {
311
            $path[] = $this->getRecord()->__toString();
312 313
        }
            
314 315 316 317 318 319 320 321 322 323
        return implode($seperator, $path);
    }

    /**
     * gets number of children (direct descendants)
     *
     * @return int            
     */     
    public function getNumberChildren()
    {
324
        return count($this->getChildren());
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    }

    /**
     * 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
     *
340 341
     * @return bool
     * @todo Wrap in transaction          
342
     */
343
    public function insertAsParentOf(Doctrine_Entity $dest)
344 345
    {
        // cannot insert a node that has already has a place within the tree
346
        if ($this->isValidNode()) {
347
            return false;
348
        }
349
        // cannot insert as parent of root
350
        if ($dest->getNode()->isRoot()) {
351
            return false;
352
        }
353
        
354
        $newLeft  = $dest->getNode()->getLeftValue();
zYne's avatar
zYne committed
355
        $newRight = $dest->getNode()->getRightValue() + 2;
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
        $newRoot  = $dest->getNode()->getRootValue();
		$newLevel = $dest->getNode()->getLevel();
		
		// Make space for new node
        $this->shiftRLValues($dest->getNode()->getRightValue() + 1, 2, $newRoot);
        
        // Slide child nodes over one and down one to allow new parent to wrap them
		$componentName = $this->_tree->getBaseComponent();		
        $q = new Doctrine_Query();
        $q->update($componentName);
        $q->set("$componentName.lft", "$componentName.lft + 1");
        $q->set("$componentName.rgt", "$componentName.rgt + 1");
        $q->set("$componentName.level", "$componentName.level + 1");
        $q->where("$componentName.lft >= ? AND $componentName.rgt <= ?", array($newLeft, $newRight));
		$q = $this->_tree->returnQueryWithRootId($q, $newRoot);
		$q->execute();
        
        $this->record['level'] = $newLevel;
		$this->insertNode($newLeft, $newRight, $newRoot);
375 376 377 378 379 380 381
        
        return true;
    }

    /**
     * inserts node as previous sibling of dest record
     *
382 383
     * @return bool
     * @todo Wrap in transaction       
384
     */
385
    public function insertAsPrevSiblingOf(Doctrine_Entity $dest)
386 387
    {
        // cannot insert a node that has already has a place within the tree
388
        if ($this->isValidNode())
389 390 391 392 393 394 395
            return false;

        $newLeft = $dest->getNode()->getLeftValue();
        $newRight = $dest->getNode()->getLeftValue() + 1;
        $newRoot = $dest->getNode()->getRootValue();
        
        $this->shiftRLValues($newLeft, 2, $newRoot);
396
        $this->record['level'] = $dest['level'];
397 398 399 400 401 402 403 404 405 406 407
        $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
     *
408 409
     * @return bool
     * @todo Wrap in transaction           
410
     */    
411
    public function insertAsNextSiblingOf(Doctrine_Entity $dest)
412 413
    {
        // cannot insert a node that has already has a place within the tree
414
        if ($this->isValidNode())
415 416 417 418 419 420 421
            return false;

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

        $this->shiftRLValues($newLeft, 2, $newRoot);
422
        $this->record['level'] = $dest['level'];
423 424 425 426 427
        $this->insertNode($newLeft, $newRight, $newRoot);

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

428
        return true;
429 430 431 432 433
    }

    /**
     * inserts node as first child of dest record
     *
434 435
     * @return bool
     * @todo Wrap in transaction         
436
     */
437
    public function insertAsFirstChildOf(Doctrine_Entity $dest)
438 439
    {
        // cannot insert a node that has already has a place within the tree
440
        if ($this->isValidNode())
441 442 443 444 445 446 447
            return false;

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

        $this->shiftRLValues($newLeft, 2, $newRoot);
448
        $this->record['level'] = $dest['level'] + 1;
449 450 451 452 453 454 455 456 457 458 459
        $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
     *
460 461
     * @return bool
     * @todo Wrap in transaction            
462
     */
463
    public function insertAsLastChildOf(Doctrine_Entity $dest)
464 465
    {
        // cannot insert a node that has already has a place within the tree
466
        if ($this->isValidNode())
467 468 469 470 471 472 473
            return false;

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

        $this->shiftRLValues($newLeft, 2, $newRoot);
474
        $this->record['level'] = $dest['level'] + 1;
475 476 477 478 479 480 481
        $this->insertNode($newLeft, $newRight, $newRoot);

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

483 484
    /**
     * Accomplishes moving of nodes between different trees.
485
     * Used by the move* methods if the root values of the two nodes are different.
486
     *
487
     * @param Doctrine_Entity $dest
488 489
     * @param unknown_type $newLeftValue
     * @param unknown_type $moveType
490
     * @todo Better exception handling/wrapping
491
     */
492
    private function _moveBetweenTrees(Doctrine_Entity $dest, $newLeftValue, $moveType)
493 494 495 496 497 498 499 500 501 502 503
    {
        $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();
504
                $oldLevel = $this->record['level'];
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
                
                // 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();
                
543 544 545
                $newLevel = $this->record['level'];
                $levelDiff = $newLevel - $oldLevel;
                
546 547
                // Relocate descendants of the node
                $diff = $this->getLeftValue() - $oldLft;
548
                $componentName = $this->_tree->getBaseComponent();
romanb's avatar
romanb committed
549
                $rootColName = $this->_tree->getAttribute('rootColumnName');
550

551 552
                // Update lft/rgt/root/level for all descendants
                $q = new Doctrine_Query($conn);
553
                $q = $q->update($componentName)
romanb's avatar
romanb committed
554 555 556 557
                        ->set($componentName . '.lft', 'lft + ?', $diff)
                        ->set($componentName . '.rgt', 'rgt + ?', $diff)
                        ->set($componentName . '.level', 'level + ?', $levelDiff)
                        ->set($componentName . '.' . $rootColName, '?', $newRoot)
558 559
                        ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?',
                        array($oldLft, $oldRgt));
560
                $q = $this->_tree->returnQueryWithRootId($q, $oldRoot);
561 562 563
                $q->execute();
                
                $conn->commit();
564
            } catch (Exception $e) {
565 566 567 568
                $conn->rollback();
                throw $e;
            }
    }
569

570 571
    /**
     * moves node as prev sibling of dest record
572
     * 
573
     */     
574
    public function moveAsPrevSiblingOf(Doctrine_Entity $dest)
575
    {
576 577 578 579 580
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue(), __FUNCTION__);
        } else {
            // Move within the tree
581 582 583
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'];
            $this->updateNode($dest->getNode()->getLeftValue(), $this->record['level'] - $oldLevel);
584
        }
585 586 587 588 589 590
    }

    /**
     * moves node as next sibling of dest record
     *        
     */
591
    public function moveAsNextSiblingOf(Doctrine_Entity $dest)
592
    {
593 594 595 596 597
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue() + 1, __FUNCTION__);
        } else {
            // Move within tree
598 599 600
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'];
            $this->updateNode($dest->getNode()->getRightValue() + 1, $this->record['level'] - $oldLevel);
601
        }
602 603 604 605 606 607
    }

    /**
     * moves node as first child of dest record
     *            
     */
608
    public function moveAsFirstChildOf(Doctrine_Entity $dest)
609
    {
610 611 612 613 614
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue() + 1, __FUNCTION__);
        } else {
            // Move within tree
615 616 617
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'] + 1;
            $this->updateNode($dest->getNode()->getLeftValue() + 1, $this->record['level'] - $oldLevel);
618
        }
619 620 621 622 623 624
    }

    /**
     * moves node as last child of dest record
     *        
     */
625
    public function moveAsLastChildOf(Doctrine_Entity $dest)
626
    {
627 628 629 630 631
        if ($dest->getNode()->getRootValue() != $this->getRootValue()) {
            // Move between trees
            $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue(), __FUNCTION__);
        } else {
            // Move within tree
632 633 634
            $oldLevel = $this->record['level'];
            $this->record['level'] = $dest['level'] + 1;
            $this->updateNode($dest->getNode()->getRightValue(), $this->record['level'] - $oldLevel);
635
        }
636
    }
637

638
    /**
639
     * Makes this node a root node. Only used in multiple-root trees.
640 641 642
     *
     * @todo Exception handling/wrapping
     */
643
    public function makeRoot($newRootId)
644 645
    {
        // TODO: throw exception instead?
romanb's avatar
romanb committed
646
        if ($this->getLeftValue() == 1 || ! $this->_tree->getAttribute('hasManyRoots')) {
647 648 649 650 651 652
            return false;
        }
        
        $oldRgt = $this->getRightValue();
        $oldLft = $this->getLeftValue();
        $oldRoot = $this->getRootValue();
653
        $oldLevel = $this->record['level'];
654 655 656 657 658
        
        try {
            $conn = $this->record->getTable()->getConnection();
            $conn->beginTransaction();
            
659
            // Detach from old tree (close gap in old tree)
660 661 662 663
            $first = $oldRgt + 1;
            $delta = $oldLft - $oldRgt - 1;
            $this->shiftRLValues($first, $delta, $this->getRootValue());
            
664
            // Set new lft/rgt/root/level values for root node
665 666
            $this->setLeftValue(1);
            $this->setRightValue($oldRgt - $oldLft + 1);
667
            $this->setRootValue($newRootId);
668
            $this->record['level'] = 0;
669
            
670
            // Update descendants lft/rgt/root/level values
671
            $diff = 1 - $oldLft;
672
            $newRoot = $newRootId;
673
            $componentName = $this->_tree->getBaseComponent();
romanb's avatar
romanb committed
674
            $rootColName = $this->_tree->getAttribute('rootColumnName');
675
            $q = new Doctrine_Query($conn);
676
            $q = $q->update($componentName)
romanb's avatar
romanb committed
677 678 679 680
                    ->set($componentName . '.lft', 'lft + ?', $diff)
                    ->set($componentName . '.rgt', 'rgt + ?', $diff)
                    ->set($componentName . '.level', 'level - ?', $oldLevel)
                    ->set($componentName . '.' . $rootColName, '?', $newRoot)
681 682
                    ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?',
                    array($oldLft, $oldRgt));
683
            $q = $this->_tree->returnQueryWithRootId($q, $oldRoot);
684 685 686
            $q->execute();
            
            $conn->commit();
687 688
            
        } catch (Exception $e) {
689 690 691 692
            $conn->rollback();
            throw $e;
        }
    }
693 694 695 696 697

    /**
     * adds node as last child of record
     *        
     */
698
    public function addChild(Doctrine_Entity $record)
699 700 701 702 703 704 705 706 707 708 709
    {
        $record->getNode()->insertAsLastChildOf($this->getRecord());
    }

    /**
     * determines if node is leaf
     *
     * @return bool            
     */
    public function isLeaf()
    {
zYne's avatar
zYne committed
710
        return (($this->getRightValue() - $this->getLeftValue()) == 1);
711 712 713 714 715 716 717 718 719
    }

    /**
     * determines if node is root
     *
     * @return bool            
     */
    public function isRoot()
    {
zYne's avatar
zYne committed
720
        return ($this->getLeftValue() == 1);
721 722 723 724 725 726 727
    }

    /**
     * determines if node is equal to subject node
     *
     * @return bool            
     */    
728
    public function isEqualTo(Doctrine_Entity $subj)
729
    {
zYne's avatar
zYne committed
730 731 732 733
        return (($this->getLeftValue() == $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() == $subj->getNode()->getRightValue()) && 
                ($this->getRootValue() == $subj->getNode()->getRootValue())
                );
734 735 736 737 738
    }

    /**
     * determines if node is child of subject node
     *
zYne's avatar
zYne committed
739
     * @return bool
740
     */
741
    public function isDescendantOf(Doctrine_Entity $subj)
742
    {
743 744 745
        return (($this->getLeftValue() > $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() < $subj->getNode()->getRightValue()) &&
                ($this->getRootValue() == $subj->getNode()->getRootValue()));
746 747 748 749 750 751 752
    }

    /**
     * determines if node is child of or sibling to subject node
     *
     * @return bool            
     */
753
    public function isDescendantOfOrEqualTo(Doctrine_Entity $subj)
754
    {
755 756 757
        return (($this->getLeftValue() >= $subj->getNode()->getLeftValue()) &&
                ($this->getRightValue() <= $subj->getNode()->getRightValue()) &&
                ($this->getRootValue() == $subj->getNode()->getRootValue()));
758 759 760 761 762
    }

    /**
     * determines if node is valid
     *
romanb's avatar
romanb committed
763
     * @return bool
764
     */
765
    public function isValidNode($record = null)
766
    {
767 768
        if ($record === null) {
          return ($this->getRightValue() > $this->getLeftValue());
769
        } else if ( $record instanceof Doctrine_Entity ) {
770
          return ($record->getNode()->getRightValue() > $record->getNode()->getLeftValue());
771 772
        } else {
          return false;
773
        }
774 775 776 777
    }

    /**
     * deletes node and it's descendants
778
     * @todo Delete more efficiently. Wrap in transaction if needed.      
779 780 781 782
     */
    public function delete()
    {
        // TODO: add the setting whether or not to delete descendants or relocate children
783
        $oldRoot = $this->getRootValue();
784
        $q = $this->_tree->getBaseQuery();
785
        
786
        $baseAlias = $this->_tree->getBaseAlias();
787
        $componentName = $this->_tree->getBaseComponent();
788

789
        $q = $q->addWhere("$baseAlias.lft >= ? AND $baseAlias.rgt <= ?", array($this->getLeftValue(), $this->getRightValue()));
790

romanb's avatar
romanb committed
791
        $q = $this->_tree->returnQueryWithRootId($q, $oldRoot);
792 793 794 795 796 797 798
        
        $coll = $q->execute();

        $coll->delete();

        $first = $this->getRightValue() + 1;
        $delta = $this->getLeftValue() - $this->getRightValue() - 1;
799
        $this->shiftRLValues($first, $delta, $oldRoot);
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        
        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
822
     * @todo Wrap in transaction
823
     */
824
    private function updateNode($destLeft, $levelDiff)
825
    { 
826
        $componentName = $this->_tree->getBaseComponent();
827 828
        $left = $this->getLeftValue();
        $right = $this->getRightValue();
829
        $rootId = $this->getRootValue();
830 831 832

        $treeSize = $right - $left + 1;

833
        // Make room in the new branch
834
        $this->shiftRLValues($destLeft, $treeSize, $rootId);
835

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

841 842 843
        // update level for descendants
        $q = new Doctrine_Query();
        $q = $q->update($componentName)
844
                ->set($componentName . '.level', 'level + ?')
845
                ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?',
846
                        array($levelDiff, $left, $right));
847 848 849
        $q = $this->_tree->returnQueryWithRootId($q, $rootId);
        $q->execute();
        
850
        // now there's enough room next to target to move the subtree
851
        $this->shiftRLRange($left, $right, $destLeft - $left, $rootId);
852

853
        // correct values after source (close gap in old tree)
854
        $this->shiftRLValues($right + 1, -$treeSize, $rootId);
855 856 857 858 859 860 861 862 863 864 865

        $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
866
    private function shiftRlValues($first, $delta, $rootId = 1)
867
    {
zYne's avatar
zYne committed
868 869
        $qLeft  = new Doctrine_Query();
        $qRight = new Doctrine_Query();
870 871

        // shift left columns
872
        $componentName = $this->_tree->getBaseComponent();
romanb's avatar
romanb committed
873
        $qLeft = $qLeft->update($componentName)
874 875
                                ->set($componentName . '.lft', 'lft + ?')
                                ->where($componentName . '.lft >= ?', array($delta, $first));
romanb's avatar
romanb committed
876
        
romanb's avatar
romanb committed
877
        $qLeft = $this->_tree->returnQueryWithRootId($qLeft, $rootId);
878 879 880 881
        
        $resultLeft = $qLeft->execute();
        
        // shift right columns
romanb's avatar
romanb committed
882
        $resultRight = $qRight->update($componentName)
883 884
                                ->set($componentName . '.rgt', 'rgt + ?')
                                ->where($componentName . '.rgt >= ?', array($delta, $first));
885

romanb's avatar
romanb committed
886
        $qRight = $this->_tree->returnQueryWithRootId($qRight, $rootId);
887 888 889 890 891 892 893 894 895 896 897 898

        $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
899
    private function shiftRlRange($first, $last, $delta, $rootId = 1)
900
    {
zYne's avatar
zYne committed
901 902
        $qLeft  = new Doctrine_Query();
        $qRight = new Doctrine_Query();
903 904

        // shift left column values
905
        $componentName = $this->_tree->getBaseComponent();
romanb's avatar
romanb committed
906
        $qLeft = $qLeft->update($componentName)
907 908
                                ->set($componentName . '.lft', 'lft + ?')
                                ->where($componentName . '.lft >= ? AND ' . $componentName . '.lft <= ?', array($delta, $first, $last));
909
        
romanb's avatar
romanb committed
910
        $qLeft = $this->_tree->returnQueryWithRootId($qLeft, $rootId);
911 912 913 914

        $resultLeft = $qLeft->execute();
        
        // shift right column values
romanb's avatar
romanb committed
915
        $qRight = $qRight->update($componentName)
916 917
                                ->set($componentName . '.rgt', 'rgt + ?')
                                ->where($componentName . '.rgt >= ? AND ' . $componentName . '.rgt <= ?', array($delta, $first, $last));
918

romanb's avatar
romanb committed
919
        $qRight = $this->_tree->returnQueryWithRootId($qRight, $rootId);
920 921 922

        $resultRight = $qRight->execute();
    }
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 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    /**
     * 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()
    {
971
        if ( ! isset($this->record['level'])) {
972
            $baseAlias = $this->_tree->getBaseAlias();
973
            $componentName = $this->_tree->getBaseComponent();
974
            $q = $this->_tree->getBaseQuery();
975
            $q = $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue()));
976

977
            $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue());
978 979 980
            
            $coll = $q->execute();

981
            $this->record['level'] = count($coll) ? count($coll) : 0;
982
        }
983
        return $this->record['level'];
984 985 986 987 988 989 990 991
    }

    /**
     * get records root id value
     *            
     */     
    public function getRootValue()
    {
992 993 994
        if ($this->_tree->getAttribute('hasManyRoots')) {
            return $this->record->get($this->_tree->getAttribute('rootColumnName'));
        }
995 996 997 998 999 1000 1001 1002 1003 1004
        return 1;
    }

    /**
     * sets records root id value
     *
     * @param int            
     */
    public function setRootValue($value)
    {
1005 1006 1007
        if ($this->_tree->getAttribute('hasManyRoots')) {
            $this->record->set($this->_tree->getAttribute('rootColumnName'), $value);   
        }    
1008
    }
1009
}