Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for iterating directly over Collection #576

Merged
merged 1 commit into from
Jan 3, 2019
Merged
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
11 changes: 10 additions & 1 deletion lib/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
*
* @package Stripe
*/
class Collection extends StripeObject
class Collection extends StripeObject implements \IteratorAggregate
{

const OBJECT_NAME = "list";
Expand Down Expand Up @@ -68,6 +68,15 @@ public function retrieve($id, $params = null, $opts = null)
return Util\Util::convertToStripeObject($response, $opts);
}

/**
* @return \ArrayIterator An iterator that can be used to iterate
* across objects in the current page.
*/
public function getIterator()
{
return new \ArrayIterator($this->data);
}

/**
* @return Util\AutoPagingIterator An iterator that can be used to iterate
* across all objects across all pages. As page boundaries are
Expand Down
22 changes: 21 additions & 1 deletion tests/Stripe/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,26 @@ public function testCanCreate()
]);
}

public function testCanIterate()
{
$seen = [];
foreach ($this->fixture as $item) {
array_push($seen, $item['id']);
}

$this->assertSame([1], $seen);
}

public function testSupportsIteratorToArray()
{
$seen = [];
foreach (iterator_to_array($this->fixture) as $item) {
array_push($seen, $item['id']);
}

$this->assertSame([1], $seen);
}

public function testProvidesAutoPagingIterator()
{
$this->stubRequest(
Expand All @@ -95,7 +115,7 @@ public function testProvidesAutoPagingIterator()
$this->assertSame([1, 2, 3], $seen);
}

public function testSupportsIteratorToArray()
public function testAutoPagingIteratorSupportsIteratorToArray()
{
$this->stubRequest(
'GET',
Expand Down