summaryrefslogtreecommitdiff
path: root/ext/spl/examples/limititerator.inc
blob: e471f5d0e469d8b9e7173b22a7c2d0d516417cb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php

class LimitIterator implements Iterator
{
	protected $it;
	protected $offset;
	protected $count;
	private $pos;

	// count === NULL means all
	function __construct(Iterator $it, $offset = 0, $count = -1)
	{
		if ($offset < 0) {
			throw new exception('Parameter offset must be > 0');
		}
		if ($count < 0 && $count != -1) {
			throw new exception('Parameter count must either be -1 or a value greater than or equal to 0');
		}
		$this->it     = $it;
		$this->offset = $offset;
		$this->count  = $count;
		$this->pos    = 0;
	}
	
	function seek($position) {
		if ($position < $this->offset) {
			throw new exception('Cannot seek to '.$position.' which is below offset '.$this->offset);
		}
		if ($position > $this->offset + $this->count && $this->count != -1) {
			throw new exception('Cannot seek to '.$position.' which is behind offset '.$this->offset.' plus count '.$this->count);
		}
		if ($this->it instanceof SeekableIterator) {
			$this->it->seek($position);
			$this->pos = $position;
		} else {
			while($this->pos < $position && $this->it->hasMore()) {
				$this->next();
			}
		}
	}

	function rewind()
	{
		$this->it->rewind();
		$this->pos = 0;
		$this->seek($this->offset);
	}
	
	function hasMore() {
		return ($this->count == -1 || $this->pos < $this->offset + $this->count)
			 && $this->it->hasMore();
	}
	
	function key() {
		return $this->it->key();
	}

	function current() {
		return $this->it->current();
	}

	function next() {
		$this->it->next();
		$this->pos++;
	}

	function getPosition() {
		return $this->pos;
	}
}

?>