Browse Source

add childCount method

QuickApps 12 years ago
parent
commit
1c4ab9708e

+ 27 - 1
src/Model/Behavior/TreeBehavior.php

@@ -73,6 +73,32 @@ class TreeBehavior extends Behavior {
 			]);
 	}
 
+/**
+ * Get the number of child nodes.
+ *
+ * @param integer|string $id The ID of the record to read
+ * @param boolean $direct whether to count direct, or all, children
+ * @return integer Number of child nodes.
+ */
+	public function childCount($id, $direct = false) {
+		$config = $this->config();
+		list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
+
+		if ($direct) {
+			return $this->_table->find()
+				->where([$parent => $id])
+				->count();
+		}
+
+		$node = $this->_table->find()
+			->select([$parent, $left, $right])
+			->where([$this->_table->primaryKey() => $id])
+			->first();
+		$node = $this->_scope($node);
+
+		return ($node->{$right} - $node->{$left} - 1) / 2;
+	}
+
 	protected function _scope($query) {
 		$config = $this->config();
 
@@ -92,4 +118,4 @@ class TreeBehavior extends Behavior {
 		return $query->matching($association->name());
 	}
 
-}
+}

+ 11 - 0
tests/Fixture/NumberTreeFixture.php

@@ -45,6 +45,17 @@ class NumberTreeFixture extends TestFixture {
 /**
  * Records
  *
+ *	- electronics:1
+ *		- televisions:2
+ *			- tube:3
+ *			- lcd:4
+ *			- plasma:5
+ *		- portable:6
+ *			- mp3:7
+ *				- flash:8
+ *			- cd:9
+ *			- radios:10
+ *
  * @var array
  */
 	public $records = array(

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

@@ -67,5 +67,30 @@ class TreeBehaviorTest extends TestCase {
 		$this->assertEquals([11], $nodes->extract('id')->toArray());
 	}
 
+/**
+ * Tests the childCount()
+ *
+ * @return void
+ */
+	public function testChildCount() {
+		// direct childs for the root node
+		$countDirect = $this->table->childCount(1, true);
+		$this->assertEquals($countDirect, 2);
 
+		// counts all the childs of root
+		$count = $this->table->childCount(1, false);
+		$this->assertEquals($count, 9);
+
+		// counts direct childs
+		$count = $this->table->childCount(2, false);
+		$this->assertEquals($count, 3);
+
+		// count childs for a middle-node
+		$count = $this->table->childCount(6, false);
+		$this->assertEquals($count, 4);
+
+		// count leaf childs
+		$count = $this->table->childCount(10, false);
+		$this->assertEquals($count, 0);
+	}
 }