Browse Source

Added Collection::buffered() to make any non-rewidable rewindable

Jose Lorenzo Rodriguez 11 years ago
parent
commit
a73697246d
2 changed files with 29 additions and 0 deletions
  1. 14 0
      src/Collection/CollectionTrait.php
  2. 15 0
      tests/TestCase/Collection/CollectionTest.php

+ 14 - 0
src/Collection/CollectionTrait.php

@@ -17,6 +17,7 @@ namespace Cake\Collection;
 use AppendIterator;
 use ArrayObject;
 use Cake\Collection\Collection;
+use Cake\Collection\Iterator\BufferedIterator;
 use Cake\Collection\Iterator\ExtractIterator;
 use Cake\Collection\Iterator\FilterIterator;
 use Cake\Collection\Iterator\InsertIterator;
@@ -890,6 +891,19 @@ trait CollectionTrait {
 	}
 
 /**
+ * Returns a new collection where the operations performed by this collection.
+ * Not matter how many times the new collection is iterated, those operations will
+ * only be performed once.
+ *
+ * This can also be used to make any non-rewindable iterator rewindable.
+ *
+ * @return \Cake\Collection\Iterator\BufferedIterator
+ */
+	public function buffered() {
+		return new BufferedIterator($this);
+	}
+
+/**
  * Returns a new collection with each of the elements of this collection
  * after flattening the tree structure. The tree structure is defined
  * by nesting elements under a key with a known name. It is possible

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

@@ -14,9 +14,11 @@
  */
 namespace Cake\Test\TestCase\Collection;
 
+use ArrayIterator;
 use ArrayObject;
 use Cake\Collection\Collection;
 use Cake\TestSuite\TestCase;
+use NoRewindIterator;
 
 /**
  * CollectionTest
@@ -646,6 +648,19 @@ class CollectionTest extends TestCase {
 	}
 
 /**
+ * Tests converting a non rewindable iterator into a rewindable one using
+ * the buffered method.
+ *
+ * @return void
+ */
+	public function testBuffered() {
+		$items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
+		$buffered = (new Collection($items))->buffered();
+		$this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
+		$this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
+	}
+
+/**
  * Tests the combine method
  *
  * @return void