AutoPagingIterator.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Stripe\Util;
  3. class AutoPagingIterator implements \Iterator
  4. {
  5. private $lastId = null;
  6. private $page = null;
  7. private $pageOffset = 0;
  8. private $params = [];
  9. public function __construct($collection, $params)
  10. {
  11. $this->page = $collection;
  12. $this->params = $params;
  13. }
  14. public function rewind()
  15. {
  16. // Actually rewinding would require making a copy of the original page.
  17. }
  18. public function current()
  19. {
  20. $item = current($this->page->data);
  21. $this->lastId = $item !== false ? $item['id'] : null;
  22. return $item;
  23. }
  24. public function key()
  25. {
  26. return key($this->page->data) + $this->pageOffset;
  27. }
  28. public function next()
  29. {
  30. $item = next($this->page->data);
  31. if ($item === false) {
  32. // If we've run out of data on the current page, try to fetch another one
  33. // and increase the offset the new page would start at
  34. $this->pageOffset += count($this->page->data);
  35. if ($this->page['has_more']) {
  36. $this->params = array_merge(
  37. $this->params ?: [],
  38. ['starting_after' => $this->lastId]
  39. );
  40. $this->page = $this->page->all($this->params);
  41. } else {
  42. return false;
  43. }
  44. }
  45. }
  46. public function valid()
  47. {
  48. $key = key($this->page->data);
  49. $valid = ($key !== null && $key !== false);
  50. return $valid;
  51. }
  52. }