1 | <?php |
||
15 | class LookaheadIterator implements \Iterator |
||
16 | { |
||
17 | /** |
||
18 | * @var \Traversable |
||
19 | */ |
||
20 | protected $iterator; |
||
21 | |||
22 | /** |
||
23 | * @var int |
||
24 | */ |
||
25 | protected $key = 0; |
||
26 | |||
27 | /** |
||
28 | * @var mixed |
||
29 | */ |
||
30 | protected $current; |
||
31 | |||
32 | /** |
||
33 | * @var bool |
||
34 | */ |
||
35 | protected $valid; |
||
36 | |||
37 | /** |
||
38 | * LookaheadIterator constructor. |
||
39 | * @param iterable $iterator |
||
40 | * @throws \InvalidArgumentException |
||
41 | */ |
||
42 | public function __construct(iterable $iterator) |
||
51 | |||
52 | /** |
||
53 | * @param iterable $iterator |
||
54 | * @return \Iterator |
||
55 | * @throws \InvalidArgumentException |
||
56 | */ |
||
57 | private function toIterator(iterable $iterator): \Iterator |
||
70 | |||
71 | /** |
||
72 | * @return mixed |
||
73 | */ |
||
74 | public function current() |
||
78 | |||
79 | /** |
||
80 | * @return int|mixed |
||
81 | */ |
||
82 | public function key() |
||
86 | |||
87 | /** |
||
88 | * Rewind the iterator to the first element. |
||
89 | * @return void |
||
90 | */ |
||
91 | public function rewind(): void |
||
96 | |||
97 | /** |
||
98 | * Move forward to next element. |
||
99 | * |
||
100 | * @return void |
||
101 | */ |
||
102 | public function next(): void |
||
115 | |||
116 | /** |
||
117 | * Check if current position is valid. |
||
118 | * |
||
119 | * @return bool |
||
120 | */ |
||
121 | public function valid(): bool |
||
125 | |||
126 | /** |
||
127 | * Check whether there is a next element. |
||
128 | * |
||
129 | * @return bool |
||
130 | */ |
||
131 | public function hasNext(): bool |
||
135 | |||
136 | /** |
||
137 | * Get next value. |
||
138 | * |
||
139 | * @return mixed |
||
140 | */ |
||
141 | public function getNext() |
||
145 | |||
146 | /** |
||
147 | * Get next key. |
||
148 | * |
||
149 | * @return mixed |
||
150 | */ |
||
151 | public function getNextKey() |
||
155 | } |
||
156 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: