MediaWiki  master
ExplodeIterator.php
Go to the documentation of this file.
1 <?php
30 class ExplodeIterator implements Iterator {
31  // The subject string
33 
34  // The delimiter
35  private $delim, $delimLength;
36 
37  // The position of the start of the line
38  private $curPos;
39 
40  // The position after the end of the next delimiter
41  private $endPos;
42 
44  private $current;
45 
51  public function __construct( $delim, $subject ) {
52  $this->subject = $subject;
53  $this->delim = $delim;
54 
55  // Micro-optimisation (theoretical)
56  $this->subjectLength = strlen( $subject );
57  $this->delimLength = strlen( $delim );
58 
59  $this->rewind();
60  }
61 
62  public function rewind() {
63  $this->curPos = 0;
64  $this->endPos = strpos( $this->subject, $this->delim );
65  $this->refreshCurrent();
66  }
67 
68  public function refreshCurrent() {
69  if ( $this->curPos === false ) {
70  $this->current = false;
71  } elseif ( $this->curPos >= $this->subjectLength ) {
72  $this->current = '';
73  } elseif ( $this->endPos === false ) {
74  $this->current = substr( $this->subject, $this->curPos );
75  } else {
76  $this->current = substr( $this->subject, $this->curPos, $this->endPos - $this->curPos );
77  }
78  }
79 
80  public function current() {
81  return $this->current;
82  }
83 
87  public function key() {
88  return $this->curPos;
89  }
90 
94  public function next() {
95  if ( $this->endPos === false ) {
96  $this->curPos = false;
97  } else {
98  $this->curPos = $this->endPos + $this->delimLength;
99  if ( $this->curPos >= $this->subjectLength ) {
100  $this->endPos = false;
101  } else {
102  $this->endPos = strpos( $this->subject, $this->delim, $this->curPos );
103  }
104  }
105  $this->refreshCurrent();
106  }
107 
111  public function valid() {
112  return $this->curPos !== false;
113  }
114 }
ExplodeIterator\$subjectLength
$subjectLength
Definition: ExplodeIterator.php:32
ExplodeIterator\$delim
$delim
Definition: ExplodeIterator.php:35
ExplodeIterator\key
key()
Definition: ExplodeIterator.php:87
ExplodeIterator\rewind
rewind()
Definition: ExplodeIterator.php:62
ExplodeIterator
An iterator which works exactly like:
Definition: ExplodeIterator.php:30
ExplodeIterator\$endPos
$endPos
Definition: ExplodeIterator.php:41
ExplodeIterator\$current
string false $current
The current token.
Definition: ExplodeIterator.php:44
ExplodeIterator\valid
valid()
Definition: ExplodeIterator.php:111
ExplodeIterator\refreshCurrent
refreshCurrent()
Definition: ExplodeIterator.php:68
ExplodeIterator\next
next()
Definition: ExplodeIterator.php:94
ExplodeIterator\$subject
$subject
Definition: ExplodeIterator.php:32
ExplodeIterator\__construct
__construct( $delim, $subject)
Construct a DelimIterator.
Definition: ExplodeIterator.php:51
ExplodeIterator\$delimLength
$delimLength
Definition: ExplodeIterator.php:35
ExplodeIterator\current
current()
Definition: ExplodeIterator.php:80
ExplodeIterator\$curPos
$curPos
Definition: ExplodeIterator.php:38