Skip to content

Commit

Permalink
Disallowing the creation of tree cycles in the TreeBehavior
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 29, 2014
1 parent 825b830 commit 9841450
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/Model/Behavior/TreeBehavior.php
Expand Up @@ -126,11 +126,18 @@ protected function _setParent($entity, $parent) {
$parentNode = $this->_getParent($parent);
$parentLeft = $parentNode->get($config['left']);
$parentRight = $parentNode->get($config['right']);

$right = $entity->get($config['right']);
$left = $entity->get($config['left']);

// Values for moving to the left
if ($parentLeft > $left && $parentLeft < $right) {
throw new \RuntimeException(sprintf(
'Cannot use node "%s" as parent for entity "%s"',
$parent,
$entity->get($this->_table->primaryKey())
));
}

// Values for moving )o the left
$diff = $right - $left + 1;
$targetLeft = $parentRight;
$targetRight = $diff + $parentRight - 1;
Expand Down
15 changes: 15 additions & 0 deletions tests/TestCase/Model/Behavior/TreeBehaviorTest.php
Expand Up @@ -486,4 +486,19 @@ public function testRootingSubTree() {
$this->assertEquals(range(1, 22), $numbers);
}

/**
* Tests that trying to create a cycle throws an exception
*
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot use node "5" as parent for entity "2"
* @return void
*/
public function testReparentCycle() {
$table = TableRegistry::get('NumberTrees');
$table->addBehavior('Tree');
$entity = $table->get(2);
$entity->parent_id = 5;
$table->save($entity);
}

}

0 comments on commit 9841450

Please sign in to comment.