paging json API iterator

raw

PagingJsonIterator.php

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
73
<?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;
    }
}
?>
 
raw

example.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$http = new HTTP_Request2();
$pi = new PagingJsonIterator(
    $http,
    'http://jira.example.com/rest/api/2/search'
    . '?startAt={startAt}'
    . '&maxResults={pageSize}'
    . '&fields=key'
    ),
    50
);
foreach ($pi as $issue) {
    echo $issue->key . "\n";
}
?>
 
Christian Weiske Christian Weiske
owner

History