Skip to content

Commit

Permalink
Cursor pagination for invoices (#1479)
Browse files Browse the repository at this point in the history
  • Loading branch information
driesvints authored Dec 6, 2022
1 parent 8fe5687 commit 9dd155b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"illuminate/http": "^9.21",
"illuminate/log": "^9.21",
"illuminate/notifications": "^9.21",
"illuminate/pagination": "^9.21",
"illuminate/routing": "^9.21",
"illuminate/support": "^9.21",
"illuminate/view": "^9.21",
Expand Down
41 changes: 41 additions & 0 deletions src/Concerns/ManagesInvoices.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace Laravel\Cashier\Concerns;

use Illuminate\Pagination\Cursor;
use Illuminate\Pagination\CursorPaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Laravel\Cashier\Exceptions\InvalidInvoice;
Expand Down Expand Up @@ -300,4 +303,42 @@ public function invoicesIncludingPending(array $parameters = [])
{
return $this->invoices(true, $parameters);
}

/**
* Get a cursor paginator for the customer's invoices.
*
* @param int|null $perPage
* @param array $parameters
* @param string $cursorName
* @param \Illuminate\Pagination\Cursor|string|null $cursor
* @return \Illuminate\Contracts\Pagination\CursorPaginator
*/
public function cursorPaginateInvoices($perPage = 24, array $parameters = [], $cursorName = 'cursor', $cursor = null)
{
if (! $cursor instanceof Cursor) {
$cursor = is_string($cursor)
? Cursor::fromEncoded($cursor)
: CursorPaginator::resolveCurrentCursor($cursorName, $cursor);
}

if (! is_null($cursor)) {
if ($cursor->pointsToNextItems()) {
$parameters['starting_after'] = $cursor->parameter('id');
} else {
$parameters['ending_before'] = $cursor->parameter('id');
}
}

$invoices = $this->invoices(true, array_merge($parameters, ['limit' => $perPage + 1]));

if (! is_null($cursor) && $cursor->pointsToPreviousItems()) {
$invoices = $invoices->reverse();
}

return new CursorPaginator($invoices, $perPage, $cursor, array_merge([
'path' => Paginator::resolveCurrentPath(),
'cursorName' => $cursorName,
'parameters' => ['id'],
]));
}
}

0 comments on commit 9dd155b

Please sign in to comment.