Skip to content

Commit

Permalink
Merge pull request #948 from baijunyao/feature/add-first-and-last-fun…
Browse files Browse the repository at this point in the history
…citon-to-collection

Add `first()` and `last()` functions to `Collection`
  • Loading branch information
richardm-stripe authored Jul 20, 2020
2 parents 7f51626 + 409c8ae commit 935036f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,26 @@ public function previousPage($params = null, $opts = null)
return $this->all($params, $opts);
}

/**
* Gets the first item from the current page. Returns `null` if the current page is empty.
*
* @return null|\Stripe\StripeObject
*/
public function first()
{
return \count($this->data) > 0 ? $this->data[0] : null;
}

/**
* Gets the last item from the current page. Returns `null` if the current page is empty.
*
* @return null|\Stripe\StripeObject
*/
public function last()
{
return \count($this->data) > 0 ? $this->data[\count($this->data) - 1] : null;
}

private function extractPathAndUpdateParams($params)
{
$url = \parse_url($this->url);
Expand Down
24 changes: 24 additions & 0 deletions tests/Stripe/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,28 @@ public function testPreviousPage()
$previousPage = $this->fixture->previousPage();
static::assertSame([], $previousPage->data);
}

public function testFirst()
{
$collection = Collection::constructFrom([
'data' => [
['content' => 'first'],
['content' => 'middle'],
['content' => 'last'],
],
]);
static::assertSame('first', $collection->first()['content']);
}

public function testLast()
{
$collection = Collection::constructFrom([
'data' => [
['content' => 'first'],
['content' => 'middle'],
['content' => 'last'],
],
]);
static::assertSame('last', $collection->last()['content']);
}
}

0 comments on commit 935036f

Please sign in to comment.