ZipIterator   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 1
dl 0
loc 60
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A newFromArguments() 0 5 1
A rewind() 0 7 2
A key() 0 4 1
A current() 0 8 2
A next() 0 6 2
A valid() 0 8 3
1
<?php
2
3
namespace itertools;
4
5
use Iterator;
6
use InvalidArgumentException;
7
8
/**
9
 * Inspired by pythons [zip](http://docs.python.org/3.1/library/functions.html#zip) function. It
10
 * can be constructed with an array of iterators and it iterates all of its arguments at the index,
11
 * returning during each iteration an array of the elements of each iterator on the same iteration positon
12
 *
13
 * Example:
14
 *     $csv1 = new FileCsvIterator('file1.csv');
15
 *     $csv2 = new FileCsvIterator('file2.csv');
16
 *     foreach(new ZipIterator(array($csv1, $csv2)) as $combinedRows) {
17
 *         $row1 = $combinedRows[0]; // a row in file1.csv
18
 *         $row2 = $combinedRows[1]; // row in file2.csv on same position
19
 *     }
20
 */
21
class ZipIterator implements Iterator
22
{
23
	protected $iterators;
24
	protected $iterationCount;
25
26
	public function __construct(array $iterators)
27
	{
28
		if(count($iterators) == 0) {
29
			throw new InvalidArgumentException('Cannot construct a ZipIterator from an empty array of iterators');
30
		}
31
		$this->iterators = array();
32
		foreach($iterators as $iterator) {
33
			$this->iterators[] = IterUtil::asIterator($iterator);
34
		}
35
	}
36
37
	public static function newFromArguments()
38
	{
39
		$iterators = func_get_args();
40
		return new self($iterators);
41
	}
42
43
    public function rewind()
44
	{
45
		$this->iterationCount = 0;
46
		foreach($this->iterators as $iterator) {
47
			$iterator->rewind();
48
		}
49
    }
50
51
    public function key()
52
	{
53
		return $this->iterationCount++;
54
    }
55
56
    public function current()
57
	{
58
		$currentValues = array();
59
		foreach($this->iterators as $iterator) {
60
			$currentValues[] = $iterator->current();
61
		}
62
		return $currentValues;
63
    }
64
65
    public function next()
66
	{
67
		foreach($this->iterators as $iterator) {
68
			$iterator->next();
69
		}
70
    }
71
72
    public function valid()
73
	{
74
		$valid = true;
75
		foreach($this->iterators as $iterator) {
76
			$valid = $iterator->valid() && $valid;
77
		}
78
		return $valid;
79
    }
80
}
81
82