AutoPagingIterator.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. class Services_Twilio_AutoPagingIterator
  3. implements Iterator
  4. {
  5. protected $generator;
  6. protected $args;
  7. protected $items;
  8. private $_args;
  9. public function __construct($generator, $page, $size, $filters) {
  10. $this->generator = $generator;
  11. $this->page = $page;
  12. $this->size = $size;
  13. $this->filters = $filters;
  14. $this->items = array();
  15. // Save a backup for rewind()
  16. $this->_args = array(
  17. 'page' => $page,
  18. 'size' => $size,
  19. 'filters' => $filters,
  20. );
  21. }
  22. public function current()
  23. {
  24. return current($this->items);
  25. }
  26. public function key()
  27. {
  28. return key($this->items);
  29. }
  30. /*
  31. * Return the next item in the list, making another HTTP call to the next
  32. * page of resources if necessary.
  33. */
  34. public function next()
  35. {
  36. try {
  37. $this->loadIfNecessary();
  38. return next($this->items);
  39. }
  40. catch (Services_Twilio_RestException $e) {
  41. // 20006 is an out of range paging error, everything else is valid
  42. if ($e->getCode() != 20006) {
  43. throw $e;
  44. }
  45. }
  46. }
  47. /*
  48. * Restore everything to the way it was before we began paging. This gets
  49. * called at the beginning of any foreach() loop
  50. */
  51. public function rewind()
  52. {
  53. foreach ($this->_args as $arg => $val) {
  54. $this->$arg = $val;
  55. }
  56. $this->items = array();
  57. $this->next_page_uri = null;
  58. }
  59. public function count()
  60. {
  61. throw new BadMethodCallException('Not allowed');
  62. }
  63. public function valid()
  64. {
  65. try {
  66. $this->loadIfNecessary();
  67. return key($this->items) !== null;
  68. }
  69. catch (Services_Twilio_RestException $e) {
  70. // 20006 is an out of range paging error, everything else is valid
  71. if ($e->getCode() != 20006) {
  72. throw $e;
  73. }
  74. }
  75. return false;
  76. }
  77. /*
  78. * Fill $this->items with a new page from the API, if necessary.
  79. */
  80. protected function loadIfNecessary()
  81. {
  82. if (// Empty because it's the first time or last page was empty
  83. empty($this->items)
  84. // null key when the items list is iterated over completely
  85. || key($this->items) === null
  86. ) {
  87. $page = call_user_func_array($this->generator, array(
  88. $this->page,
  89. $this->size,
  90. $this->filters,
  91. $this->next_page_uri,
  92. ));
  93. $this->next_page_uri = $page->next_page_uri;
  94. $this->items = $page->getItems();
  95. $this->page = $this->page + 1;
  96. }
  97. }
  98. }