1 | <?php |
||
10 | class MapIterator implements Iterator, \JsonSerializable |
||
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() |
||
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() |
||
94 | |||
95 | public function jsonSerialize() |
||
99 | } |
||
100 |