php-src/ext/spl/examples/limititerator.inc

72 lines
1.5 KiB
PHP
Raw Normal View History

<?php
class LimitIterator implements Iterator
{
protected $it;
protected $offset;
protected $count;
2003-12-06 19:03:17 +00:00
private $pos;
// count === NULL means all
2003-12-06 19:03:17 +00:00
function __construct(Iterator $it, $offset = 0, $count = -1)
{
2003-12-06 19:03:17 +00:00
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;
2003-12-06 19:03:17 +00:00
$this->pos = 0;
}
2003-12-06 19:03:17 +00:00
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);
}
2003-11-18 22:18:38 +00:00
if ($this->it instanceof SeekableIterator) {
2003-12-06 19:03:17 +00:00
$this->it->seek($position);
$this->pos = $position;
} else {
2003-12-06 19:03:17 +00:00
while($this->pos < $position && $this->it->hasMore()) {
$this->next();
}
}
}
2003-12-06 19:03:17 +00:00
function rewind()
{
$this->it->rewind();
$this->pos = 0;
$this->seek($this->offset);
}
function hasMore() {
2003-12-06 19:03:17 +00:00
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();
2003-12-06 19:03:17 +00:00
$this->pos++;
}
function getPosition() {
return $this->pos;
}
}
?>