MapIterator::valid()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Mouf\Database\TDBM;
6
7
use Iterator;
8
9
/**
10
 * An iterator that maps element of another iterator by calling a callback on it.
11
 */
12
class MapIterator implements Iterator, \JsonSerializable
13
{
14
    /**
15
     * @var Iterator
16
     */
17
    protected $iterator;
18
19
    /**
20
     * @var callable Modifies the current item in iterator
21
     */
22
    protected $callable;
23
24
    /**
25
     * @param $iterator Iterator|array
26
     * @param $callable callable This can have two parameters
27
     *
28
     * @throws TDBMException
29
     */
30
    public function __construct($iterator, callable $callable)
31
    {
32
        if (is_array($iterator)) {
33
            $this->iterator = new \ArrayIterator($iterator);
34
        } elseif (!($iterator instanceof Iterator)) {
35
            throw new TDBMException('$iterator parameter must be an instance of Iterator');
36
        } else {
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
     *
58
     * @return mixed
59
     */
60
    public function current()
61
    {
62
        $callable = $this->callable;
63
64
        return $callable($this->iterator->current());
65
    }
66
67
    public function next()
68
    {
69
        $this->iterator->next();
70
    }
71
72
    public function key()
73
    {
74
        return $this->iterator->key();
75
    }
76
77
    public function valid()
78
    {
79
        return $this->iterator->valid();
80
    }
81
82
    public function rewind()
83
    {
84
        $this->iterator->rewind();
85
    }
86
87
    /**
88
     * Casts the iterator to a PHP array.
89
     *
90
     * @return array
91
     */
92
    public function toArray()
93
    {
94
        return iterator_to_array($this);
95
    }
96
97
    public function jsonSerialize()
98
    {
99
        return $this->toArray();
100
    }
101
}
102