Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Naoray committed Oct 26, 2023
1 parent 4a87609 commit eafd22e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 29 deletions.
27 changes: 1 addition & 26 deletions src/Endpoints/CollectionEndpointAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,32 +56,7 @@ protected function rest_iterator(?string $from = null, ?int $limit = null, array
/** @var CursorCollection $page */
$page = $this->rest_list($from, $limit, $filters);

return $this->iterate($page, $iterateBackwards);
}

/**
* Iterate over a CursorCollection and yield its elements.
*
* @param CursorCollection $page
* @param bool $iterateBackwards
*
* @return Generator
*/
protected function iterate(CursorCollection $page, bool $iterateBackwards = false): Generator
{
while (true) {
foreach ($page as $item) {
yield $item;
}

if (($iterateBackwards && ! $page->hasPrevious()) || ! $page->hasNext()) {
break;
}

$page = $iterateBackwards
? $page->previous()
: $page->next();
}
return $page->getAutoIterator($iterateBackwards);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Endpoints/SubscriptionEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,6 @@ public function iterator(?string $from = null, ?int $limit = null, array $parame
{
$page = $this->page($from, $limit, $parameters);

return $this->iterate($page, $iterateBackwards);
return $page->getAutoIterator($iterateBackwards);
}
}
31 changes: 29 additions & 2 deletions src/Resources/CursorCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Mollie\Api\Resources;

use Generator;
use Mollie\Api\MollieApiClient;

abstract class CursorCollection extends BaseCollection
Expand Down Expand Up @@ -36,7 +37,7 @@ abstract protected function createResourceObject();
*/
final public function next()
{
if (! $this->hasNext()) {
if (!$this->hasNext()) {
return null;
}

Expand All @@ -59,7 +60,7 @@ final public function next()
*/
final public function previous()
{
if (! $this->hasPrevious()) {
if (!$this->hasPrevious()) {
return null;
}

Expand Down Expand Up @@ -93,4 +94,30 @@ public function hasPrevious()
{
return isset($this->_links->previous->href);
}

/**
* Iterate over a CursorCollection and yield its elements.
*
* @param boolean $iterateBackwards
*
* @return Generator
*/
public function getAutoIterator(bool $iterateBackwards = false): Generator
{
$page = $this;

while (true) {
foreach ($page as $item) {
yield $item;
}

if (($iterateBackwards && !$page->hasPrevious()) || !$page->hasNext()) {
break;
}

$page = $iterateBackwards
? $page->previous()
: $page->next();
}
}
}

0 comments on commit eafd22e

Please sign in to comment.