summaryrefslogtreecommitdiff
path: root/ext/spl/examples/limititerator.inc
blob: 1b0e927a2ea6be977584aed666853abc8ce49730 (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
<?php

class LimitIterator implements Iterator
{
	protected $it;
	protected $offset;
	protected $count;
	protected $index;

	// negative offset is  respected
	// count === NULL means all
	function __construct(Iterator $it, $offset = 0, $count = NULL)
	{
		$this->it     = $it;
		$this->offset = $offset;
		$this->count  = $count;
		$this->index  = 0;
	}
	
	function rewind()
	{
		$this->it->rewind();
		$this->index = 0;
		if ($this->it instanceof SeekableIterator) {
			$this->index = $this->it->seek($this->offset);
		} else {
			while($this->index < $this->offset && $this->it->hasMore()) {
				$this->next();
			}
		}
	}
	
	function hasMore() {
		return (is_null($this->count) || $this->index < $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->index++;
	}
}

?>