MediaWiki  REL1_24
MappedIterator.php
Go to the documentation of this file.
00001 <?php
00029 class MappedIterator extends FilterIterator {
00031     protected $vCallback;
00033     protected $aCallback;
00035     protected $cache = array();
00036 
00037     protected $rewound = false; // boolean; whether rewind() has been called
00038 
00054     public function __construct( $iter, $vCallback, array $options = array() ) {
00055         if ( is_array( $iter ) ) {
00056             $baseIterator = new ArrayIterator( $iter );
00057         } elseif ( $iter instanceof Iterator ) {
00058             $baseIterator = $iter;
00059         } else {
00060             throw new UnexpectedValueException( "Invalid base iterator provided." );
00061         }
00062         parent::__construct( $baseIterator );
00063         $this->vCallback = $vCallback;
00064         $this->aCallback = isset( $options['accept'] ) ? $options['accept'] : null;
00065     }
00066 
00067     public function next() {
00068         $this->cache = array();
00069         parent::next();
00070     }
00071 
00072     public function rewind() {
00073         $this->rewound = true;
00074         $this->cache = array();
00075         parent::rewind();
00076     }
00077 
00078     public function accept() {
00079         $value = call_user_func( $this->vCallback, $this->getInnerIterator()->current() );
00080         $ok = ( $this->aCallback ) ? call_user_func( $this->aCallback, $value ) : true;
00081         if ( $ok ) {
00082             $this->cache['current'] = $value;
00083         }
00084 
00085         return $ok;
00086     }
00087 
00088     public function key() {
00089         $this->init();
00090 
00091         return parent::key();
00092     }
00093 
00094     public function valid() {
00095         $this->init();
00096 
00097         return parent::valid();
00098     }
00099 
00100     public function current() {
00101         $this->init();
00102         if ( parent::valid() ) {
00103             return $this->cache['current'];
00104         } else {
00105             return null; // out of range
00106         }
00107     }
00108 
00112     protected function init() {
00113         if ( !$this->rewound ) {
00114             $this->rewind();
00115         }
00116     }
00117 }