1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gielfeldt\Iterators; |
4
|
|
|
|
5
|
|
|
class OrderedInterleaveIterator extends \SplHeap |
6
|
|
|
{ |
7
|
|
|
const DEFAULT_COMPARE = [__CLASS__, 'defaultCompare']; |
8
|
|
|
|
9
|
|
|
protected $iterators; |
10
|
|
|
protected $compareFunction = self::DEFAULT_COMPARE; |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
public function __construct(\Traversable ...$iterators) |
14
|
|
|
{ |
15
|
|
|
$this->iterators = new \ArrayIterator(); |
16
|
|
|
foreach ($iterators as $iterator) { |
17
|
|
|
$this->add($iterator); |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function setCompare($compareFunction) |
22
|
|
|
{ |
23
|
|
|
$this->compareFunction = $compareFunction; |
24
|
|
|
return $this; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function compare($a, $b) |
28
|
|
|
{ |
29
|
|
|
return call_user_func_array($this->compareFunction, [$b[2], $a[2]]); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function defaultCompare($a, $b) |
33
|
|
|
{ |
34
|
|
|
return $a <=> $b; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function add(\Traversable $iterator) |
38
|
|
|
{ |
39
|
|
|
$this->iterators->append($iterator instanceof \Iterator ? $iterator : new \IteratorIterator($iterator)); |
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function rewind() |
44
|
|
|
{ |
45
|
|
|
while (!$this->isEmpty()) { |
46
|
|
|
$this->extract(); |
47
|
|
|
} |
48
|
|
|
foreach ($this->iterators as $no => $iterator) { |
49
|
|
|
$iterator->rewind(); |
50
|
|
|
if ($iterator->valid()) { |
51
|
|
|
$this->insert([$no, $iterator->key(), $iterator->current()]); |
52
|
|
|
$iterator->next(); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
$this->idx = 0; |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function key() |
59
|
|
|
{ |
60
|
|
|
return $this->top()[1]; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function current() |
64
|
|
|
{ |
65
|
|
|
return $this->top()[2]; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function next() |
69
|
|
|
{ |
70
|
|
|
$this->idx++; |
71
|
|
|
$used = $this->extract(); |
72
|
|
|
$no = $used[0]; |
73
|
|
|
if ($this->iterators[$no]->valid()) { |
74
|
|
|
$this->insert([$no, $this->iterators[$no]->key(), $this->iterators[$no]->current()]); |
75
|
|
|
$this->iterators[$no]->next(); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: