Add method to get depth of tree's node.

Backported from 3.0.
This commit is contained in:
ADmad 2015-02-01 13:11:44 +05:30
parent 7866605c71
commit 54fe7ed204
2 changed files with 55 additions and 0 deletions

View file

@ -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
*

View file

@ -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
*