1 | <?php |
||
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() |
||
69 | |||
70 | public function key() |
||
74 | |||
75 | public function valid() |
||
79 | |||
80 | public function rewind() |
||
84 | |||
85 | /** |
||
86 | * Casts the iterator to a PHP array. |
||
87 | * |
||
88 | * @return array |
||
89 | */ |
||
90 | public function toArray() { |
||
93 | } |
||
94 |