Skip to content

Commit

Permalink
Implemented delete logic
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 29, 2014
1 parent 78ae995 commit 99c8877
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Model/Behavior/TreeBehavior.php
Expand Up @@ -111,6 +111,20 @@ public function beforeSave(Event $event, Entity $entity) {
}
}

public function beforeDelete(Event $event, Entity $entity) {
$config = $this->config();
$left = $entity->get($config['left']);
$right = $entity->get($config['right']);
$diff = $right - $left + 1;

if ($diff > 2) {
$this->_table->deleteAll(['left >=' => $left + 1, 'left <=' => $right - 1]);
return;
}

$this->_sync($diff, '-' , "> {$right}");
}

/**
* Returns an entity with the left and right columns for the parent node
* of the node specified by the passed id.
Expand Down
15 changes: 15 additions & 0 deletions tests/TestCase/Model/Behavior/TreeBehaviorTest.php
Expand Up @@ -507,4 +507,19 @@ public function testReparentCycle() {
$table->save($entity);
}

/**
* Tests deleting a leaf in the tree
*
* @return void
*/
public function testDeleteLeaf() {
$table = TableRegistry::get('NumberTrees');
$table->addBehavior('Tree');
$entity = $table->get(4);
$this->assertTrue($table->delete($entity));
$result = $table->find()->order('lft')->hydrate(false)->toArray();
$table->recover();
$expected = $table->find()->order('lft')->hydrate(false)->toArray();
$this->assertEquals($expected, $result);
}
}

0 comments on commit 99c8877

Please sign in to comment.