Browse Source

Extract formatTreeList() from findTreeList()

Mark Scherer 10 years ago
parent
commit
f64dfb9add
1 changed files with 34 additions and 12 deletions
  1. 34 12
      src/ORM/Behavior/TreeBehavior.php

+ 34 - 12
src/ORM/Behavior/TreeBehavior.php

@@ -455,21 +455,43 @@ class TreeBehavior extends Behavior
      */
     public function findTreeList(Query $query, array $options)
     {
-        return $this->_scope($query)
+        $results = $this->_scope($query)
             ->find('threaded', [
                 'parentField' => $this->config('parent'),
                 'order' => [$this->config('left') => 'ASC']
-            ])
-            ->formatResults(function ($results) use ($options) {
-                $options += [
-                    'keyPath' => $this->_getPrimaryKey(),
-                    'valuePath' => $this->_table->displayField(),
-                    'spacer' => '_'
-                ];
-                return $results
-                    ->listNested()
-                    ->printer($options['valuePath'], $options['keyPath'], $options['spacer']);
-            });
+            ]);
+        return $this->formatTreeList($results, $options);
+    }
+
+    /**
+     * Formats query as a flat list where the keys are
+     * the primary key for the table and the values are the display field for the table.
+     * Values are prefixed to visually indicate relative depth in the tree.
+     *
+     * Available options are:
+     *
+     * - keyPath: A dot separated path to fetch the field to use for the array key, or a closure to
+     *  return the key out of the provided row.
+     * - valuePath: A dot separated path to fetch the field to use for the array value, or a closure to
+     *  return the value out of the provided row.
+     * - spacer: A string to be used as prefix for denoting the depth in the tree for each item
+     *
+     * @param \Cake\ORM\Query $query
+     * @param array $options Array of options as described above
+     * @return \Cake\ORM\Query
+     */
+    public function formatTreeList(Query $query, array $options = [])
+    {
+        return $query->formatResults(function ($results) use ($options) {
+            $options += [
+                'keyPath' => $this->_getPrimaryKey(),
+                'valuePath' => $this->_table->displayField(),
+                'spacer' => '_'
+            ];
+            return $results
+                ->listNested()
+                ->printer($options['valuePath'], $options['keyPath'], $options['spacer']);
+        });
     }
 
     /**