Skip to content

Commit 54fe7ed

Browse files
committed
Add method to get depth of tree's node.
Backported from 3.0.
1 parent 7866605 commit 54fe7ed

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

lib/Cake/Model/Behavior/TreeBehavior.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -996,6 +996,41 @@ public function verify(Model $Model) {
996996
return true;
997997
}
998998

999+
/**
1000+
* Returns the depth level of a node in the tree.
1001+
*
1002+
* @param Model $Model Model using this behavior
1003+
* @param int|string $id The primary key for record to get the level of.
1004+
* @return int|bool Integer of the level or false if the node does not exist.
1005+
*/
1006+
public function getLevel(Model $Model, $id = null) {
1007+
if ($id === null) {
1008+
$id = $Model->id;
1009+
}
1010+
1011+
$node = $Model->find('first', array(
1012+
'conditions' => array($Model->escapeField() => $id),
1013+
'order' => false,
1014+
'recursive' => -1
1015+
));
1016+
1017+
if (empty($node)) {
1018+
return false;
1019+
}
1020+
1021+
extract($this->settings[$Model->alias]);
1022+
1023+
return $Model->find('count', array(
1024+
'conditions' => array(
1025+
$scope,
1026+
$left . ' <' => $node[$Model->alias][$left],
1027+
$right . ' >' => $node[$Model->alias][$right]
1028+
),
1029+
'order' => false,
1030+
'recursive' => -1
1031+
));
1032+
}
1033+
9991034
/**
10001035
* Sets the parent of the given node
10011036
*

lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,26 @@ public function testMovePromote() {
548548
$this->assertTrue($validTree);
549549
}
550550

551+
/**
552+
* testGetLevel method
553+
*
554+
* @return void
555+
*/
556+
public function testGetLevel() {
557+
extract($this->settings);
558+
$this->Tree = new $modelClass();
559+
$this->Tree->initialize(2, 2);
560+
$this->Tree->id = null;
561+
562+
$result = $this->Tree->getLevel(5);
563+
$this->assertEquals(1, $result);
564+
565+
$result = $this->Tree->getLevel(3);
566+
$this->assertEquals(2, $result);
567+
568+
$this->assertFalse($this->Tree->getLevel(999));
569+
}
570+
551571
/**
552572
* testMoveWithWhitelist method
553573
*

0 commit comments

Comments
 (0)