3 * Convenience class for generating iterators from iterators.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Aaron Schulz
25 * Convenience class for generating iterators from iterators.
29 class MappedIterator
implements Iterator
{
31 protected $baseIterator;
36 * Build an new iterator from a base iterator by having the former wrap the
37 * later, returning the result of "value" callback for each current() invocation.
38 * The callback takes the result of current() on the base iterator as an argument.
39 * The keys of the base iterator are reused verbatim.
41 * @param Iterator|Array $iter
42 * @param Closure $vCallback
45 public function __construct( $iter, Closure
$vCallback ) {
46 if ( is_array( $iter ) ) {
47 $this->baseIterator
= new ArrayIterator( $iter );
48 } elseif ( $iter instanceof Iterator
) {
49 $this->baseIterator
= $iter;
51 throw new MWException( "Invalid base iterator provided." );
53 $this->vCallback
= $vCallback;
59 public function rewind() {
60 $this->baseIterator
->rewind();
64 * @return Mixed|null Returns null if out of range
66 public function current() {
67 if ( !$this->baseIterator
->valid() ) {
68 return null; // out of range
70 return call_user_func_array( $this->vCallback
, array( $this->baseIterator
->current() ) );
74 * @return Mixed|null Returns null if out of range
76 public function key() {
77 if ( !$this->baseIterator
->valid() ) {
78 return null; // out of range
80 return $this->baseIterator
->key();
86 public function next() {
87 $this->baseIterator
->next();
93 public function valid() {
94 return $this->baseIterator
->valid();