diff --git a/lib/Cake/Model/Behavior/TreeBehavior.php b/lib/Cake/Model/Behavior/TreeBehavior.php index 11bbb5bb1..1cb3f003f 100644 --- a/lib/Cake/Model/Behavior/TreeBehavior.php +++ b/lib/Cake/Model/Behavior/TreeBehavior.php @@ -996,6 +996,41 @@ class TreeBehavior extends ModelBehavior { return true; } +/** + * Returns the depth level of a node in the tree. + * + * @param Model $Model Model using this behavior + * @param int|string $id The primary key for record to get the level of. + * @return int|bool Integer of the level or false if the node does not exist. + */ + public function getLevel(Model $Model, $id = null) { + if ($id === null) { + $id = $Model->id; + } + + $node = $Model->find('first', array( + 'conditions' => array($Model->escapeField() => $id), + 'order' => false, + 'recursive' => -1 + )); + + if (empty($node)) { + return false; + } + + extract($this->settings[$Model->alias]); + + return $Model->find('count', array( + 'conditions' => array( + $scope, + $left . ' <' => $node[$Model->alias][$left], + $right . ' >' => $node[$Model->alias][$right] + ), + 'order' => false, + 'recursive' => -1 + )); + } + /** * Sets the parent of the given node * diff --git a/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php b/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php index f03ac2a79..e5503f563 100644 --- a/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php +++ b/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php @@ -548,6 +548,26 @@ class TreeBehaviorNumberTest extends CakeTestCase { $this->assertTrue($validTree); } +/** + * testGetLevel method + * + * @return void + */ + public function testGetLevel() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $result = $this->Tree->getLevel(5); + $this->assertEquals(1, $result); + + $result = $this->Tree->getLevel(3); + $this->assertEquals(2, $result); + + $this->assertFalse($this->Tree->getLevel(999)); + } + /** * testMoveWithWhitelist method *