Skip to content

Commit

Permalink
Making adding new node as a descendat of a root work
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 29, 2014
1 parent c70718b commit ca226c9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Model/Behavior/TreeBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public function beforeSave(Event $event, Entity $entity) {
$edge = $parentNode->get($config['right']);
$entity->set($config['left'], $edge);
$entity->set($config['right'], $edge + 1);
$this->_sync(2, '+', ">= {$config['right']}");
$this->_sync(2, '+', ">= {$edge}");
}

if ($isNew && !$parent) {
Expand All @@ -102,9 +102,11 @@ public function beforeSave(Event $event, Entity $entity) {

protected function _getParent($id) {
$config = $this->config();
$primaryKey = (array)$this->_table->primaryKey();
$parentNode = $this->_scope($this->_table->find())
->select([$config['lft'], $config['rght']])
->where([$primaryKey[0] => $parent]);
->select([$config['left'], $config['right']])
->where([$primaryKey[0] => $id])
->first();

if (!$parentNode) {
throw new \Cake\ORM\Error\RecordNotFoundException(
Expand Down
23 changes: 23 additions & 0 deletions tests/TestCase/Model/Behavior/TreeBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,4 +324,27 @@ public function testAddOrphan() {
$this->assertEquals($expected, $results);
}

/**
* Tests that adding a child node as a decendant of one of the roots works
*
* @return void
*/
public function testAddMiddle() {
$table = TableRegistry::get('NumberTrees');
$table->addBehavior('Tree');
$entity = new Entity(
['name' => 'laptops', 'parent_id' => 1],
['markNew' => true]
);
$this->assertSame($entity, $table->save($entity));
$results = $table->find()->order('lft')->hydrate(false)->toArray();
$this->assertEquals(20, $entity->lft);
$this->assertEquals(21, $entity->rght);

$expected = $table->find()->order('lft')->hydrate(false)->toArray();
$table->recover();
$result = $table->find()->order('lft')->hydrate(false)->toArray();
$this->assertEquals($expected, $results);
}

}

0 comments on commit ca226c9

Please sign in to comment.