diff --git a/Iterator/ItemIteratorTrait.php b/Iterator/ItemIteratorTrait.php index 560fb4b..da8694f 100644 --- a/Iterator/ItemIteratorTrait.php +++ b/Iterator/ItemIteratorTrait.php @@ -113,7 +113,7 @@ public function next() $this->pageIndex++; $this->position++; - if (count($this->pageIterator->current()) <= $this->pageIndex && $this->pageIterator->nextResultToken()) { + if (count($this->pageIterator->current()) <= $this->pageIndex && $this->nextResultToken()) { $this->pageIterator->next(); $this->pageIndex = 0; } @@ -126,10 +126,23 @@ public function next() */ public function valid() { - if (isset($this->pageIterator->current()[$this->pageIndex])) { + $page = $this->pageIterator->current(); + + if (isset($page[$this->pageIndex])) { return true; } + // If there are no results, but a token for the next page + // exists let's continue paging until there are results. + while ($this->nextResultToken()) { + $this->pageIterator->next(); + $page = $this->pageIterator->current(); + + if (isset($page[$this->pageIndex])) { + return true; + } + } + return false; } } diff --git a/Iterator/PageIteratorTrait.php b/Iterator/PageIteratorTrait.php index 80c580b..6131b69 100644 --- a/Iterator/PageIteratorTrait.php +++ b/Iterator/PageIteratorTrait.php @@ -171,11 +171,17 @@ public function rewind() */ public function current() { - if (!$this->page) { + if ($this->page === null) { $this->page = $this->executeCall(); } - return $this->get($this->itemsPath, $this->page); + $page = $this->get($this->itemsPath, $this->page); + + if ($this->nextResultToken()) { + return $page ?: []; + } + + return $page; } /** @@ -196,12 +202,9 @@ public function key() public function next() { $this->position++; - - if ($this->nextResultToken()) { - $this->page = $this->executeCall(); - } else { - $this->page = null; - } + $this->page = $this->nextResultToken() + ? $this->executeCall() + : null; } /**