Skip to content
Permalink
Browse files

Initial implementation of serializable collections

  • Loading branch information...
lorenzo committed Jul 6, 2015
1 parent fa01bb1 commit 5ded2c0eedcd411c592cd2eda4ba0423aafaa42d
@@ -19,12 +19,13 @@
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 @@ public function __construct($items)
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.
@@ -16,13 +16,14 @@
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 @@ public function count()
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;
}
}
@@ -1433,4 +1433,18 @@ public function testUnfoldedExtract()
$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());
}
}

0 comments on commit 5ded2c0

Please sign in to comment.
You can’t perform that action at this time.