Last active
December 20, 2015 02:09
-
-
Save TheDistantSea/6054423 to your computer and use it in GitHub Desktop.
ZipIterator: iterates over multiple traversables in parallel. Requirements: PHP 5.4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ZipIterator implements \Iterator | |
{ | |
const ZIP_ALL = '{6087F687-D674-4549-AFBF-8D4DC07FE06F}'; | |
private $_iterators; | |
private $_zipAll = false; | |
public function __construct() | |
{ | |
foreach (func_get_args() as $argument) { | |
if ($argument === self::ZIP_ALL) { | |
$this->_zipAll = true; | |
} | |
else if (is_array($argument)) { | |
$this->_iterators[] = new \ArrayIterator($argument); | |
} | |
else if ($argument instanceof \Traversable) { | |
$this->_iterators[] = $argument; | |
} | |
else { | |
throw new Exception("All arguments to ".__CLASS__." must be arrays or implement Traversable."); | |
} | |
} | |
} | |
public function current() | |
{ | |
$result = []; | |
foreach ($this->_iterators as $iterator) { | |
$result[] = $iterator->current(); | |
} | |
return $result; | |
} | |
public function next() | |
{ | |
foreach ($this->_iterators as $iterator) { | |
$iterator->next(); | |
} | |
} | |
public function key() | |
{ | |
$result = []; | |
foreach ($this->_iterators as $iterator) { | |
$result[] = $iterator->key(); | |
} | |
return $result; | |
} | |
public function valid() | |
{ | |
foreach ($this->_iterators as $iterator) { | |
if ($iterator->valid() ^ !$this->_zipAll) { | |
return $this->_zipAll; | |
} | |
} | |
return !$this->_zipAll; | |
} | |
public function rewind() | |
{ | |
foreach ($this->_iterators as $iterator) { | |
$iterator->rewind(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment