MediaWiki  REL1_22
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 MWException( "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         return $ok;
00085     }
00086 
00087     public function key() {
00088         $this->init();
00089         return parent::key();
00090     }
00091 
00092     public function valid() {
00093         $this->init();
00094         return parent::valid();
00095     }
00096 
00097     public function current() {
00098         $this->init();
00099         if ( parent::valid() ) {
00100             return $this->cache['current'];
00101         } else {
00102             return null; // out of range
00103         }
00104     }
00105 
00109     protected function init() {
00110         if ( !$this->rewound ) {
00111             $this->rewind();
00112         }
00113     }
00114 }