MediaWiki REL1_34
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
36 protected $rewound = false; // boolean; whether rewind() has been called
37
54 public function __construct( $iter, $vCallback, array $options = [] ) {
55 if ( is_array( $iter ) ) {
56 $baseIterator = new ArrayIterator( $iter );
57 } elseif ( $iter instanceof Iterator ) {
58 $baseIterator = $iter;
59 } else {
60 throw new UnexpectedValueException( "Invalid base iterator provided." );
61 }
62 parent::__construct( $baseIterator );
63 $this->vCallback = $vCallback;
64 $this->aCallback = $options['accept'] ?? null;
65 }
66
67 public function next() {
68 $this->cache = [];
69 parent::next();
70 }
71
72 public function rewind() {
73 $this->rewound = true;
74 $this->cache = [];
75 parent::rewind();
76 }
77
78 public function accept() {
79 $value = call_user_func( $this->vCallback, $this->getInnerIterator()->current() );
80 $ok = ( $this->aCallback ) ? call_user_func( $this->aCallback, $value ) : true;
81 if ( $ok ) {
82 $this->cache['current'] = $value;
83 }
84
85 return $ok;
86 }
87
88 public function key() {
89 $this->init();
90
91 return parent::key();
92 }
93
94 public function valid() {
95 $this->init();
96
97 return parent::valid();
98 }
99
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}
Convenience class for generating iterators from iterators.
__construct( $iter, $vCallback, array $options=[])
Build an new iterator from a base iterator by having the former wrap the later, returning the result ...
init()
Obviate the usual need for rewind() before using a FilterIterator in a manual loop.