MediaWiki master
MappedIterator.php
Go to the documentation of this file.
1<?php
9namespace Wikimedia\Iterators;
10
11use ArrayIterator;
12use FilterIterator;
13use Iterator;
14use UnexpectedValueException;
15
21class MappedIterator extends FilterIterator {
23 protected $vCallback;
25 protected $aCallback;
27 protected $cache = [];
28
30 protected $rewound = false;
31
48 public function __construct( $iter, $vCallback, array $options = [] ) {
49 if ( is_array( $iter ) ) {
50 $baseIterator = new ArrayIterator( $iter );
51 } elseif ( $iter instanceof Iterator ) {
52 $baseIterator = $iter;
53 } else {
54 throw new UnexpectedValueException( "Invalid base iterator provided." );
55 }
56 parent::__construct( $baseIterator );
57 $this->vCallback = $vCallback;
58 $this->aCallback = $options['accept'] ?? null;
59 }
60
61 public function next(): void {
62 $this->cache = [];
63 parent::next();
64 }
65
66 public function rewind(): void {
67 $this->rewound = true;
68 $this->cache = [];
69 parent::rewind();
70 }
71
72 public function accept(): bool {
73 $inner = $this->getInnerIterator();
74 '@phan-var Iterator $inner';
75 $value = ( $this->vCallback )( $inner->current() );
76 $ok = ( $this->aCallback ) ? ( $this->aCallback )( $value ) : true;
77 if ( $ok ) {
78 $this->cache['current'] = $value;
79 }
80
81 return $ok;
82 }
83
85 #[\ReturnTypeWillChange]
86 public function key() {
87 $this->init();
88
89 return parent::key();
90 }
91
92 public function valid(): bool {
93 $this->init();
94
95 return parent::valid();
96 }
97
99 #[\ReturnTypeWillChange]
100 public function current() {
101 $this->init();
102 if ( parent::valid() ) {
103 return $this->cache['current'];
104 } else {
105 return null; // out of range
106 }
107 }
108
112 protected function init() {
113 if ( !$this->rewound ) {
114 $this->rewind();
115 }
116 }
117}
118
120class_alias( MappedIterator::class, 'MappedIterator' );
Convenience class for generating iterators from iterators.
init()
Obviate the usual need for rewind() before using a FilterIterator in a manual loop.
__construct( $iter, $vCallback, array $options=[])
Build a new iterator from a base iterator by having the former wrap the later, returning the result o...
bool $rewound
whether rewind() has been called