Browse Source

Started to implement a tree printer method

Jose Lorenzo Rodriguez 12 years ago
parent
commit
b86a1f4c48

+ 24 - 0
src/Collection/Iterator/TreeIterator.php

@@ -15,6 +15,7 @@
 namespace Cake\Collection\Iterator;
 
 use Cake\Collection\CollectionTrait;
+use Cake\Collection\Iterator\TreePrinter;
 use RecursiveIteratorIterator;
 
 /**
@@ -26,4 +27,27 @@ class TreeIterator extends RecursiveIteratorIterator {
 
 	use CollectionTrait;
 
+	protected $_mode;
+
+	public function __construct($items, $mode = RecursiveIteratorIterator::LEAVES_ONLY, $flags = 0) {
+		parent::__construct($items, $mode, $flags);
+		$this->_mode = $mode;
+	}
+
+	public function printer($valuePath, $keyPath = null, $spacer = '__') {
+		if (!$keyPath) {
+			$counter = 0;
+			$keyPath = function() use ($counter) {
+				return $counter++;
+			};
+		}
+		return new TreePrinter(
+			$this->getInnerIterator(),
+			$valuePath,
+			$keyPath,
+			$spacer,
+			$this->_mode
+		);
+	}
+
 }

+ 17 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -937,4 +937,21 @@ class CollectionTest extends TestCase {
 		});
 		$this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
 	}
+
+	public function testPrinter() {
+		$items = [
+			[
+				'id' => 1,
+				'name' => 'a',
+				'stuff' => [
+					['id' => 2, 'name' => 'b', 'stuff' => [['id' => 3, 'name' => 'c']]]
+				]
+			],
+			['id' => 4, 'name' => 'd', 'stuff' => [['id' => 5, 'name' => 'e']]]
+		];
+		$printer = (new Collection($items))->listNested('desc', 'stuff')->printer('name');
+		foreach ($printer as $k => $p) {
+			debug([$k => $p]);
+		}
+	}
 }