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