From 5f7d8c25232566810389c038203bcbf0eb984588 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Wed, 26 Mar 2014 22:40:55 +0100 Subject: [PATCH] Started to implement moving a subtree as a root --- src/Model/Behavior/TreeBehavior.php | 19 +++++++++++++++++- .../Model/Behavior/TreeBehaviorTest.php | 20 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/Model/Behavior/TreeBehavior.php b/src/Model/Behavior/TreeBehavior.php index a59499cfb18..1fdab20ded5 100644 --- a/src/Model/Behavior/TreeBehavior.php +++ b/src/Model/Behavior/TreeBehavior.php @@ -91,13 +91,17 @@ public function beforeSave(Event $event, Entity $entity) { if ($isNew && !$parent) { $edge = $this->_getMax(); - $entity->set($config['left'],$edge + 1); + $entity->set($config['left'], $edge + 1); $entity->set($config['right'], $edge + 2); } if (!$isNew && $dirty && $parent) { $this->_setParent($entity, $parent); } + + if (!$isNew && $dirty && !$parent) { + $this->_setAsRoot($entity); + } } protected function _getParent($id) { @@ -161,6 +165,19 @@ protected function _setParent($entity, $parent) { $entity->set($config['right'], $targetRight); } + protected function _setAsRoot($entity) { + $config = $this->config(); + $edge = $this->_getMax(); + $right = $entity->get($config['right']); + $left = $entity->get($config['left']); + $internalLeft = $left + 1; + $internalRight = $right - 1; + + $entity->set($config['left'], $edge + 1); + $entity->set($config['right'], $edge + $right - 1); + $this->_sync($edge - 1, '+', "BETWEEN {$internalLeft} AND {$internalRight}"); + } + public function findPath($query, $options) { if (empty($options['for'])) { throw new \InvalidArgumentException("The 'for' key is required for find('path')"); diff --git a/tests/TestCase/Model/Behavior/TreeBehaviorTest.php b/tests/TestCase/Model/Behavior/TreeBehaviorTest.php index a4a86fe8c7f..b0b3ac766a2 100644 --- a/tests/TestCase/Model/Behavior/TreeBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/TreeBehaviorTest.php @@ -460,4 +460,24 @@ public function testReParentLeafRight() { $this->assertEquals(range(1, 22), $numbers); } +/** + * Tests moving as a new root + * + * @return void + */ + public function testRootingSubTree() { + $table = TableRegistry::get('NumberTrees'); + $table->addBehavior('Tree'); + $entity = $table->get(2); + $entity->parent_id = null; + $this->assertSame($entity, $table->save($entity)); + $this->assertEquals(23, $entity->lft); + $this->assertEquals(30, $entity->rght); + + $result = $table->find()->order('lft')->hydrate(false)->toArray(); + $table->recover(); + $expected = $table->find()->order('lft')->hydrate(false)->toArray(); + $this->assertEquals($expected, $result); + } + }