Browse Source

Adding a method to get the depth of a tree node to the TreeBehavior.

See https://github.com/cakephp/cakephp/issues/4553
Florian Krämer 11 years ago
parent
commit
78e9979177
2 changed files with 43 additions and 1 deletions
  1. 27 1
      src/ORM/Behavior/TreeBehavior.php
  2. 16 0
      tests/TestCase/ORM/Behavior/TreeBehaviorTest.php

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

@@ -61,7 +61,8 @@ class TreeBehavior extends Behavior
             'moveUp' => 'moveUp',
             'moveDown' => 'moveDown',
             'recover' => 'recover',
-            'removeFromTree' => 'removeFromTree'
+            'removeFromTree' => 'removeFromTree',
+            'getLevel' => 'getLevel'
         ],
         'parent' => 'parent_id',
         'left' => 'lft',
@@ -792,4 +793,29 @@ class TreeBehavior extends Behavior
         }
         return $this->_primaryKey;
     }
+
+/**
+ * Returns the depth level of a node in the tree.
+ *
+ * @param int|string $id
+ * @return int|bool Integer of the level or false if the node does not exist.
+ */
+    public function getLevel($id) {
+        $config = $this->config();
+        $entity = $this->_table->find('all')
+            ->select([$config['left'], $config['right']])
+            ->where([$this->_getPrimaryKey() => $id])
+            ->first();
+
+        if ($entity === null) {
+            return false;
+        }
+
+        $query = $this->_table->find('all')->where([
+            $config['left'] . ' <' => $entity[$config['left']],
+            $config['right'] . ' >'=> $entity[$config['right']]
+        ]);
+
+        return $this->_scope($query)->count();
+    }
 }

+ 16 - 0
tests/TestCase/ORM/Behavior/TreeBehaviorTest.php

@@ -858,6 +858,22 @@ class TreeBehaviorTest extends TestCase
     }
 
     /**
+     * Tests getting the depth level of a node in the tree.
+     *
+     * @return void
+     */
+    public function testGetLevel() {
+        $result = $this->table->getLevel(8);
+        $this->assertEquals(3, $result);
+
+        $result = $this->table->getLevel(5);
+        $this->assertEquals(2, $result);
+
+        $result = $this->table->getLevel(99999);
+        $this->assertFalse($result);
+    }
+
+    /**
      * Custom assertion use to verify tha a tree is returned in the expected order
      * and that it is still valid
      *