Skip to content

Instantly share code, notes, and snippets.

@drslump
Created December 31, 2009 15:08
Show Gist options
  • Save drslump/266759 to your computer and use it in GitHub Desktop.
Save drslump/266759 to your computer and use it in GitHub Desktop.
<?php
/**
* Wraps an iterator allowing to obtain chunks of it as simple arrays
*
* It mimics the behaviour of the array_chunk() function.
*
* @license Public Domain
* @author Iván -DrSlump- Montes <drslump_at_pollinimini_dot_net>
*/
class ChunkIterator implements Iterator, OuterIterator
{
/** @var Traversable */
protected $_it;
/** @var Int */
protected $_size;
/** @var Int */
protected $_count;
/** @var array */
protected $_current;
/** @var bool */
protected $_preserve;
/**
*
* @param Iterator $it The inner iterator or an array
* @param Int $size The size of chunks
* @param Bool $preserveKeys If true preserves the original keys
*/
public function __construct($it, $size, $preserveKeys = false)
{
if (is_array($it)) {
$it = new ArrayIterator($it);
}
$this->_it = $it;
$this->_size = $size;
$this->_preserve = $preserveKeys;
$this->_count = 0;
}
public function getInnerIterator()
{
return $this->_it;
}
public function rewind()
{
$this->_it->rewind();
$this->_count = 0;
$this->_current = null;
$this->_consume();
}
public function current()
{
return $this->_current;
}
public function valid()
{
return count($this->_current) > 0;
}
public function key()
{
return $this->_count-1;
}
public function next()
{
$this->_consume();
}
/**
* Consume the inner iterator to fill up a chunk
*
*/
protected function _consume()
{
$this->_current = array();
for ($i=0; $this->_it->valid() && $i<$this->_size; $i++) {
$k = $this->_preserve ? $this->_it->key() : $i;
$this->_current[$k] = $this->_it->current();
$this->_it->next();
}
$this->_count++;
}
}
<?php
function phptal_tales_chunk($src, $nothrow)
{
$parts = explode(' ', trim($src));
$size = array_pop($parts);
$src = implode(' ', $parts);
return 'new ChunkIterator(' . phptal_tales($src, $nothrow) . ', ' . $size . ')';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment