Browse Source

Implemented delete logic

Jose Lorenzo Rodriguez 12 years ago
parent
commit
99c8877da2

+ 14 - 0
src/Model/Behavior/TreeBehavior.php

@@ -111,6 +111,20 @@ class TreeBehavior extends Behavior {
 		}
 	}
 
+	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.

+ 15 - 0
tests/TestCase/Model/Behavior/TreeBehaviorTest.php

@@ -507,4 +507,19 @@ class TreeBehaviorTest extends TestCase {
 		$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);
+	}
 }