1
|
|
|
<?php |
2
|
|
|
namespace Mouf\Database\TDBM; |
3
|
|
|
|
4
|
|
|
use Iterator; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* An iterator that maps element of another iterator by calling a callback on it. |
9
|
|
|
*/ |
10
|
|
|
class MapIterator implements Iterator { |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @var Iterator |
14
|
|
|
*/ |
15
|
|
|
protected $iterator; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var callable Modifies the current item in iterator |
19
|
|
|
*/ |
20
|
|
|
protected $callable; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param $iterator Iterator|array |
24
|
|
|
* @param $callable callable This can have two parameters |
25
|
|
|
* @throws TDBMException |
26
|
|
|
*/ |
27
|
|
|
public function __construct($iterator, callable $callable) { |
28
|
|
|
if (is_array($iterator)) { |
29
|
|
|
$this->iterator = new \ArrayIterator($iterator); |
30
|
|
|
} |
31
|
|
|
elseif (!($iterator instanceof Iterator)) |
32
|
|
|
{ |
33
|
|
|
throw new TDBMException("\$iterator parameter must be an instance of Iterator"); |
34
|
|
|
} |
35
|
|
|
else |
36
|
|
|
{ |
37
|
|
|
$this->iterator = $iterator; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if ($callable instanceof \Closure) { |
41
|
|
|
// make sure there's one argument |
42
|
|
|
$reflection = new \ReflectionObject($callable); |
43
|
|
|
if ($reflection->hasMethod('__invoke')) { |
44
|
|
|
$method = $reflection->getMethod('__invoke'); |
45
|
|
|
if ($method->getNumberOfParameters() !== 1) { |
46
|
|
|
throw new TDBMException("\$callable must accept one and only one parameter."); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$this->callable = $callable; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Alters the current item with $this->callable and returns a new item. |
56
|
|
|
* Be careful with your types as we can't do static type checking here! |
57
|
|
|
* @return mixed |
58
|
|
|
*/ |
59
|
|
|
public function current() |
60
|
|
|
{ |
61
|
|
|
$callable = $this->callable; |
62
|
|
|
return $callable($this->iterator->current()); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function next() |
66
|
|
|
{ |
67
|
|
|
$this->iterator->next(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function key() |
71
|
|
|
{ |
72
|
|
|
return $this->iterator->key(); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function valid() |
76
|
|
|
{ |
77
|
|
|
return $this->iterator->valid(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function rewind() |
81
|
|
|
{ |
82
|
|
|
$this->iterator->rewind(); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* Casts the iterator to a PHP array. |
87
|
|
|
* |
88
|
|
|
* @return array |
89
|
|
|
*/ |
90
|
|
|
public function toArray() { |
91
|
|
|
return iterator_to_array($this); |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|