Browse Source

Implemented TreeBehavior::findTreeList

Jose Lorenzo Rodriguez 12 years ago
parent
commit
fc5990f52e

+ 16 - 0
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 @@ class TreeBehavior extends Behavior {
 			]);
 	}
 
+	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.

+ 46 - 0
tests/TestCase/Model/Behavior/TreeBehaviorTest.php

@@ -159,6 +159,52 @@ class TreeBehaviorTest extends TestCase {
 	}
 
 /**
+ * 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
  *
  * @return void