From 3efc88bad36a5a88dda530e2406cd69d32ac5a0a Mon Sep 17 00:00:00 2001 From: Olivier Bellone Date: Thu, 3 Jan 2019 18:21:58 +0100 Subject: [PATCH] Add support for iterating directly over Collection --- lib/Collection.php | 11 ++++++++++- tests/Stripe/CollectionTest.php | 22 +++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/Collection.php b/lib/Collection.php index 64fd9f328..986cd3309 100644 --- a/lib/Collection.php +++ b/lib/Collection.php @@ -12,7 +12,7 @@ * * @package Stripe */ -class Collection extends StripeObject +class Collection extends StripeObject implements \IteratorAggregate { const OBJECT_NAME = "list"; @@ -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 diff --git a/tests/Stripe/CollectionTest.php b/tests/Stripe/CollectionTest.php index 560085aed..14b710d2b 100644 --- a/tests/Stripe/CollectionTest.php +++ b/tests/Stripe/CollectionTest.php @@ -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( @@ -95,7 +115,7 @@ public function testProvidesAutoPagingIterator() $this->assertSame([1, 2, 3], $seen); } - public function testSupportsIteratorToArray() + public function testAutoPagingIteratorSupportsIteratorToArray() { $this->stubRequest( 'GET',