diff --git a/src/Model/Behavior/TreeBehavior.php b/src/Model/Behavior/TreeBehavior.php index e2372d957ce..7dfe84ac06e 100644 --- a/src/Model/Behavior/TreeBehavior.php +++ b/src/Model/Behavior/TreeBehavior.php @@ -39,6 +39,7 @@ class TreeBehavior extends Behavior { 'implementedFinders' => [ 'path' => 'findPath', 'children' => 'findChildren', + 'treeList' => 'findTreeList' ], 'implementedMethods' => [ 'childCount' => 'childCount', @@ -327,6 +328,21 @@ public function findChildren($query, $options) { ]); } + public function findTreeList($query, $options) { + return $this->_scope($query) + ->find('threaded', ['parentField' => $this->config()['parent']]) + ->formatResults(function($results) use ($options) { + $options += [ + 'keyPath' => $this->_table->primaryKey(), + 'valuePath' => $this->_table->displayField(), + 'spacer' => '_' + ]; + return $results + ->listNested() + ->printer($options['valuePath'], $options['keyPath'], $options['spacer']); + }); + } + /** * Removes the current node from the tree, by positioning it as a new root * and reparents all children up one level. diff --git a/tests/TestCase/Model/Behavior/TreeBehaviorTest.php b/tests/TestCase/Model/Behavior/TreeBehaviorTest.php index a490ce3df24..b871cc02a14 100644 --- a/tests/TestCase/Model/Behavior/TreeBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/TreeBehaviorTest.php @@ -158,6 +158,52 @@ public function testFindChildrenException() { $query = $table->find('children', ['for' => 500]); } +/** + * Tests the find('treeList') method + * + * @return void + */ + public function testFindTreeList() { + $table = TableRegistry::get('MenuLinkTrees'); + $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); + $result = $table->find('treeList')->toArray(); + $expected = [ + 1 => 'Link 1', + 2 => '_Link 2', + 3 => '_Link 3', + 4 => '__Link 4', + 5 => '___Link 5', + 6 => 'Link 6', + 7 => '_Link 7', + 8 => 'Link 8' + ]; + $this->assertEquals($expected, $result); + } + +/** + * Tests the find('treeList') method with custom options + * + * @return void + */ + public function testFindTreeListCustom() { + $table = TableRegistry::get('MenuLinkTrees'); + $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); + $result = $table + ->find('treeList', ['keyPath' => 'url', 'valuePath' => 'id', 'spacer' => ' ']) + ->toArray(); + $expected = [ + '/link1.html' => '1', + 'http://example.com' => ' 2', + '/what/even-more-links.html' => ' 3', + '/lorem/ipsum.html' => ' 4', + '/what/the.html' => ' 5', + '/yeah/another-link.html' => '6', + 'http://cakephp.org' => ' 7', + '/page/who-we-are.html' => '8' + ]; + $this->assertEquals($expected, $result); + } + /** * Tests the moveUp() method *