Skip to content

Commit

Permalink
Add method to get depth of tree's node.
Browse files Browse the repository at this point in the history
Backported from 3.0.
  • Loading branch information
ADmad committed Feb 1, 2015
1 parent 7866605 commit 54fe7ed
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
35 changes: 35 additions & 0 deletions lib/Cake/Model/Behavior/TreeBehavior.php
Expand Up @@ -996,6 +996,41 @@ public function verify(Model $Model) {
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
*
Expand Down
20 changes: 20 additions & 0 deletions lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php
Expand Up @@ -548,6 +548,26 @@ public function testMovePromote() {
$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
*
Expand Down

0 comments on commit 54fe7ed

Please sign in to comment.