1: <?php
2: namespace Pharborist;
3:
4: 5: 6:
7: class TokenIterator {
8: 9: 10: 11:
12: private $tokens;
13:
14: 15: 16: 17:
18: private $position;
19:
20: 21: 22: 23:
24: private $length;
25:
26: 27: 28:
29: public function __construct(array $tokens) {
30: $this->tokens = $tokens;
31: $this->length = count($tokens);
32: $this->position = 0;
33: }
34:
35: 36: 37: 38:
39: public function current() {
40: if ($this->position >= $this->length) {
41: return NULL;
42: }
43: return $this->tokens[$this->position];
44: }
45:
46: 47: 48: 49: 50:
51: public function peek($offset) {
52: if ($this->position + $offset >= $this->length) {
53: return NULL;
54: }
55: return $this->tokens[$this->position + $offset];
56: }
57:
58: 59: 60: 61:
62: public function next() {
63: $this->position++;
64: if ($this->position >= $this->length) {
65: $this->position = $this->length;
66: return NULL;
67: }
68: return $this->tokens[$this->position];
69: }
70:
71: 72: 73: 74:
75: public function hasNext() {
76: return $this->position < $this->length;
77: }
78:
79: 80: 81: 82:
83: public function getSourcePosition() {
84: if ($this->length === 0) {
85: return new SourcePosition(1, 1);
86: }
87: $token = $this->current();
88: if ($token === NULL) {
89: $token = $this->tokens[$this->length - 1];
90: $source_position = $token->getSourcePosition();
91: $line_no = $source_position->getLineNumber();
92: $col_no = $source_position->getColumnNumber();
93: $length = strlen($token->getText());
94: return new SourcePosition($line_no, $col_no + $length);
95: }
96: return $token->getSourcePosition();
97: }
98: }
99: