Skip to content

Commit

Permalink
Initial implementation of serializable collections
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jul 6, 2015
1 parent fa01bb1 commit 5ded2c0
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/Collection/Collection.php
Expand Up @@ -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;
Expand All @@ -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.
Expand Down
20 changes: 19 additions & 1 deletion src/Collection/Iterator/BufferedIterator.php
Expand Up @@ -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
{

/**
Expand Down Expand Up @@ -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;
}
}
14 changes: 14 additions & 0 deletions tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -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.