Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions Core/src/Iterator/PageIteratorTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ trait PageIteratorTrait
*/
private $initialResultToken;

/**
* @var bool
*/
private $isInitialized = false;

/**
* @param callable $resultMapper Maps a result.
* @param callable $call The call to execute.
Expand Down Expand Up @@ -142,15 +147,13 @@ public function nextResultToken()
}

/**
* Rewind the iterator.
*
* @return null
* Set up the initial pagination state and tokens.
*/
#[\ReturnTypeWillChange]
public function rewind()
private function initialize()
{
$this->itemCount = 0;
$this->position = 0;
if ($this->isInitialized) {
return;
}

if ($this->config['firstPage']) {
list($this->page, $shouldContinue) = $this->mapResults($this->config['firstPage']);
Expand All @@ -163,6 +166,23 @@ public function rewind()
if ($nextResultToken) {
$this->set($this->resultTokenPath, $this->callOptions, $nextResultToken);
}

$this->isInitialized = true;
}

/**
* Rewind the iterator.
*
* @return null
*/
#[\ReturnTypeWillChange]
public function rewind()
{
$this->isInitialized = false;
$this->initialize();

$this->itemCount = 0;
$this->position = 0;
}

/**
Expand All @@ -173,6 +193,10 @@ public function rewind()
#[\ReturnTypeWillChange]
public function current()
{
if (!$this->isInitialized) {
$this->initialize();
}
Comment on lines +196 to +198

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit but if(!$this->isInitialized) is redundant since we also check that in $this->initialize();


if ($this->page === null) {
$this->page = $this->executeCall();
}
Expand Down
27 changes: 27 additions & 0 deletions Core/tests/Unit/Iterator/PageIteratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,33 @@ public function iteratorDataProvider()
];
}

public function testCurrentWithoutRewindUsesFirstPage()
{
$hasCalledNetwork = false;
$call = function (array $options) use (&$hasCalledNetwork) {
$hasCalledNetwork = true;
return ['items' => ['should-not-reach-here']];
};

$pages = new PageIterator(
function ($result) {
return strtoupper($result);
},
$call,
['itemsKey' => 'items'],
[
'firstPage' => [
'items' => self::$page1
]
]
);

$currentPage = $pages->current();

$this->assertFalse($hasCalledNetwork);
$this->assertEquals(array_map('strtoupper', self::$page1), $currentPage);
}

public function theCall(array $options)
{
$options += [
Expand Down
Loading