MediaWiki master
MappedIterator.php
Go to the documentation of this file.
1<?php
14class MappedIterator extends FilterIterator {
16 protected $vCallback;
18 protected $aCallback;
20 protected $cache = [];
21
23 protected $rewound = false;
24
41 public function __construct( $iter, $vCallback, array $options = [] ) {
42 if ( is_array( $iter ) ) {
43 $baseIterator = new ArrayIterator( $iter );
44 } elseif ( $iter instanceof Iterator ) {
45 $baseIterator = $iter;
46 } else {
47 throw new UnexpectedValueException( "Invalid base iterator provided." );
48 }
49 parent::__construct( $baseIterator );
50 $this->vCallback = $vCallback;
51 $this->aCallback = $options['accept'] ?? null;
52 }
53
54 public function next(): void {
55 $this->cache = [];
56 parent::next();
57 }
58
59 public function rewind(): void {
60 $this->rewound = true;
61 $this->cache = [];
62 parent::rewind();
63 }
64
65 public function accept(): bool {
66 $inner = $this->getInnerIterator();
67 '@phan-var Iterator $inner';
68 $value = ( $this->vCallback )( $inner->current() );
69 $ok = ( $this->aCallback ) ? ( $this->aCallback )( $value ) : true;
70 if ( $ok ) {
71 $this->cache['current'] = $value;
72 }
73
74 return $ok;
75 }
76
78 #[\ReturnTypeWillChange]
79 public function key() {
80 $this->init();
81
82 return parent::key();
83 }
84
85 public function valid(): bool {
86 $this->init();
87
88 return parent::valid();
89 }
90
92 #[\ReturnTypeWillChange]
93 public function current() {
94 $this->init();
95 if ( parent::valid() ) {
96 return $this->cache['current'];
97 } else {
98 return null; // out of range
99 }
100 }
101
105 protected function init() {
106 if ( !$this->rewound ) {
107 $this->rewind();
108 }
109 }
110}
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