<?php
class PagingJsonIterator implements Iterator
{
    protected $http;
    protected $url;
    protected $pageSize;
    protected $totalCount;

    public $jsonVarTotal = 'total';
    public $jsonVarStartAt = 'startAt';
    public $jsonVarPageSize = 'maxResults';
    public $jsonVarData = 'issues';

    public function __construct(HTTP_Request2 $http, $url, $pageSize = 50)
    {
        $this->http = $http;
        $this->url = $url;
        $this->pageSize = $pageSize;
    }

    public function rewind()
    {
        $this->position = 0;
        $this->loadData();
    }

    public function current()
    {
        return $this->data[$this->position - $this->dataPos];
    }

    public function key()
    {
        return $this->position;
    }

    public function next()
    {
        ++$this->position;
    }

    public function valid()
    {
        if (isset($this->data[$this->position - $this->dataPos])) {
            return true;
        }
        if ($this->position >= $this->totalCount) {
            //no more data
            return false;
        }
        $this->loadData();
        return isset($this->data[$this->position - $this->dataPos]);
    }

    protected function loadData()
    {
        $hreq = clone $this->http;
        $hreq->setUrl(
            str_replace(
                array('{startAt}', '{pageSize}'),
                array($this->position, $this->pageSize),
                $this->url
            )
        );
        $res = $hreq->send();
        $obj = json_decode($res->getBody());
        $this->totalCount = $obj->{$this->jsonVarTotal};
        $this->data = $obj->{$this->jsonVarData};
        $this->dataPos = $this->position;
    }
}
?>
