Browse Source

Add recoverSort to TreeBehavior

Berry Goudswaard 10 years ago
parent
commit
e42b536325

+ 4 - 2
src/ORM/Behavior/TreeBehavior.php

@@ -71,7 +71,8 @@ class TreeBehavior extends Behavior
         'left' => 'lft',
         'right' => 'rght',
         'scope' => null,
-        'level' => null
+        'level' => null,
+        'recoverOrder' => null
     ];
 
     /**
@@ -774,11 +775,12 @@ class TreeBehavior extends Behavior
         list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
         $primaryKey = $this->_getPrimaryKey();
         $aliasedPrimaryKey = $this->_table->aliasField($primaryKey);
+        $order = $config['recoverOrder'] ? $config['recoverOrder'] : $aliasedPrimaryKey;
 
         $query = $this->_scope($this->_table->query())
             ->select([$aliasedPrimaryKey])
             ->where([$this->_table->aliasField($parent) . ' IS' => $parentId])
-            ->order([$aliasedPrimaryKey])
+            ->order($order)
             ->hydrate(false);
 
         $leftCounter = $counter;

+ 25 - 7
tests/TestCase/ORM/Behavior/TreeBehaviorTest.php

@@ -696,13 +696,6 @@ class TreeBehaviorTest extends TestCase
     {
         $table = TableRegistry::get('MenuLinkTrees');
         $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
-        $expected = $table->find()
-            ->where(['menu' => 'main-menu'])
-            ->order('lft')
-            ->hydrate(false)
-            ->toArray();
-
-
         $table->updateAll(['lft' => null, 'rght' => null], ['menu' => 'main-menu']);
         $table->recover();
 
@@ -736,6 +729,31 @@ class TreeBehaviorTest extends TestCase
     }
 
     /**
+     * Test recover function with a custom order clause
+     *
+     * @return void
+     */
+    public function testRecoverWithCustomOrder()
+    {
+        $table = TableRegistry::get('MenuLinkTrees');
+        $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu'], 'recoverOrder' => ['MenuLinkTrees.title' => 'desc']]);
+        $table->updateAll(['lft' => null, 'rght' => null], ['menu' => 'main-menu']);
+        $table->recover();
+
+        $expected = [
+            ' 1: 2 -  8:Link 8',
+            ' 3: 6 -  6:Link 6',
+            '_ 4: 5 -  7:Link 7',
+            ' 7:16 -  1:Link 1',
+            '_ 8:13 -  3:Link 3',
+            '__ 9:12 -  4:Link 4',
+            '___10:11 -  5:Link 5',
+            '_14:15 -  2:Link 2'
+        ];
+        $this->assertMpttValues($expected, $table);
+    }
+
+    /**
      * Tests adding a new orphan node
      *
      * @return void