|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Mouf\Database\TDBM; |
|
4
|
|
|
|
|
5
|
|
|
use Iterator; |
|
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
|
|
|
* |
|
26
|
|
|
* @throws TDBMException |
|
27
|
|
|
*/ |
|
28
|
|
|
public function __construct($iterator, callable $callable) |
|
29
|
|
|
{ |
|
30
|
|
|
if (is_array($iterator)) { |
|
31
|
|
|
$this->iterator = new \ArrayIterator($iterator); |
|
32
|
|
|
} elseif (!($iterator instanceof Iterator)) { |
|
33
|
|
|
throw new TDBMException('$iterator parameter must be an instance of Iterator'); |
|
34
|
|
|
} else { |
|
35
|
|
|
$this->iterator = $iterator; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
if ($callable instanceof \Closure) { |
|
39
|
|
|
// make sure there's one argument |
|
40
|
|
|
$reflection = new \ReflectionObject($callable); |
|
41
|
|
|
if ($reflection->hasMethod('__invoke')) { |
|
42
|
|
|
$method = $reflection->getMethod('__invoke'); |
|
43
|
|
|
if ($method->getNumberOfParameters() !== 1) { |
|
44
|
|
|
throw new TDBMException('$callable must accept one and only one parameter.'); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$this->callable = $callable; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Alters the current item with $this->callable and returns a new item. |
|
54
|
|
|
* Be careful with your types as we can't do static type checking here! |
|
55
|
|
|
* |
|
56
|
|
|
* @return mixed |
|
57
|
|
|
*/ |
|
58
|
|
|
public function current() |
|
59
|
|
|
{ |
|
60
|
|
|
$callable = $this->callable; |
|
61
|
|
|
|
|
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
|
|
|
{ |
|
92
|
|
|
return iterator_to_array($this); |
|
93
|
|
|
} |
|
94
|
|
|
} |
|
95
|
|
|
|