1 : <?php
2 :
3 : class Services_Twilio_AutoPagingIterator
4 : implements Iterator
5 : {
6 : protected $generator;
7 : protected $promoter;
8 : protected $args;
9 : protected $items;
10 :
11 : private $_args;
12 :
13 : public function __construct($generator, $promoter, array $args) {
14 2 : $this->generator = $generator;
15 2 : $this->promoter = $promoter;
16 2 : $this->args = $args;
17 2 : $this->items = array();
18 :
19 : // Save a backup for rewind()
20 2 : $this->_args = $args;
21 2 : }
22 :
23 : public function current()
24 : {
25 2 : return current($this->items);
26 : }
27 :
28 : public function key()
29 : {
30 0 : return key($this->items);
31 : }
32 :
33 : public function next()
34 : {
35 : try {
36 1 : $this->loadIfNecessary();
37 1 : return next($this->items);
38 : }
39 0 : catch (Services_Twilio_RestException $e) {
40 : // 20006 is an out of range paging error, everything else is valid
41 0 : if ($e->getCode() != 20006) {
42 0 : throw $e;
43 : }
44 : }
45 0 : }
46 :
47 : public function rewind()
48 : {
49 2 : $this->args = $this->_args;
50 2 : $this->items = array();
51 2 : }
52 :
53 : public function count()
54 : {
55 0 : throw new BadMethodCallException('Not allowed');
56 : }
57 :
58 : public function valid()
59 : {
60 : try {
61 2 : $this->loadIfNecessary();
62 2 : return key($this->items) !== null;
63 : }
64 1 : catch (Services_Twilio_RestException $e) {
65 : // 20006 is an out of range paging error, everything else is valid
66 1 : if ($e->getCode() != 20006) {
67 0 : throw $e;
68 : }
69 : }
70 1 : return false;
71 : }
72 :
73 : protected function loadIfNecessary()
74 : {
75 : if (// Empty because it's the first time or last page was empty
76 2 : empty($this->items)
77 : // null key when the items list is iterated over completely
78 1 : || key($this->items) === null
79 2 : ) {
80 2 : $this->items = call_user_func_array($this->generator, $this->args);
81 2 : $this->args = call_user_func_array($this->promoter, $this->args);
82 2 : }
83 2 : }
84 : }
|