AutoPagingIterator.php
1.36 KB
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
<?php
namespace Stripe\Util;
class AutoPagingIterator implements \Iterator
{
private $lastId = null;
private $page = null;
private $params = array();
public function __construct($collection, $params)
{
$this->page = $collection;
$this->params = $params;
}
public function rewind()
{
// Actually rewinding would require making a copy of the original page.
}
public function current()
{
$item = current($this->page->data);
$this->lastId = $item !== false ? $item['id'] : null;
return $item;
}
public function key()
{
return key($this->page->data);
}
public function next()
{
$item = next($this->page->data);
if ($item === false) {
// If we've run out of data on the current page, try to fetch another one
if ($this->page['has_more']) {
$this->params = array_merge(
$this->params ? $this->params : array(),
array('starting_after' => $this->lastId)
);
$this->page = $this->page->all($this->params);
} else {
return false;
}
}
}
public function valid()
{
$key = key($this->page->data);
$valid = ($key !== null && $key !== false);
return $valid;
}
}