Browse Source

Initial implementation of serializable collections

Jose Lorenzo Rodriguez 10 years ago
parent
commit
5ded2c0eed

+ 12 - 1
src/Collection/Collection.php

@@ -19,12 +19,13 @@ use Cake\Collection\CollectionInterface;
 use Cake\Collection\CollectionTrait;
 use InvalidArgumentException;
 use IteratorIterator;
+use Serializable;
 
 /**
  * A collection is an immutable list of elements with a handful of functions to
  * iterate, group, transform and extract information from it.
  */
-class Collection extends IteratorIterator implements CollectionInterface
+class Collection extends IteratorIterator implements CollectionInterface, Serializable
 {
 
     use CollectionTrait;
@@ -49,6 +50,16 @@ class Collection extends IteratorIterator implements CollectionInterface
         parent::__construct($items);
     }
 
+    public function serialize()
+    {
+        return serialize($this->buffered());
+    }
+
+    public function unserialize($collection)
+    {
+        $this->__construct(unserialize($collection));
+    }
+
     /**
      * Returns an array that can be used to describe the internal state of this
      * object.

+ 19 - 1
src/Collection/Iterator/BufferedIterator.php

@@ -16,13 +16,14 @@ namespace Cake\Collection\Iterator;
 
 use Cake\Collection\Collection;
 use Countable;
+use Serializable;
 use SplDoublyLinkedList;
 
 /**
  * Creates an iterator from another iterator that will keep the results of the inner
  * iterator in memory, so that results don't have to be re-calculated.
  */
-class BufferedIterator extends Collection implements Countable
+class BufferedIterator extends Collection implements Countable, Serializable
 {
 
     /**
@@ -176,4 +177,21 @@ class BufferedIterator extends Collection implements Countable
 
         return $this->_buffer->count();
     }
+
+    public function serialize()
+    {
+        if (!$this->_finished) {
+            $this->count();
+        }
+
+        return serialize($this->_buffer);
+    }
+
+    public function unserialize($buffer)
+    {
+        $this->__construct([]);
+        $this->_buffer = unserialize($buffer);
+        $this->_started = true;
+        $this->_finished = true;
+    }
 }

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

@@ -1433,4 +1433,18 @@ class CollectionTest extends TestCase
         $expected = [1, 2, 3, 4, 5, null, 6];
         $this->assertEquals($expected, $extracted->toList());
     }
+
+    /**
+     * Tests serializing a simple collection
+     *
+     * @return void
+     */
+    public function testSerializeSimpleCollection()
+    {
+        $collection = new Collection([1, 2, 3]);
+        $selialized = serialize($collection);
+        $unserialized = unserialize($selialized);
+        $this->assertEquals($collection->toList(), $unserialized->toList());
+        $this->assertEquals($collection->toArray(), $unserialized->toArray());
+    }
 }