From 9dd155b1dca0fd831b339399f516ad7c9d2b61ba Mon Sep 17 00:00:00 2001 From: Dries Vints Date: Tue, 6 Dec 2022 15:20:10 +0100 Subject: [PATCH] Cursor pagination for invoices (#1479) --- composer.json | 1 + src/Concerns/ManagesInvoices.php | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/composer.json b/composer.json index 3a76de67..5fce35db 100644 --- a/composer.json +++ b/composer.json @@ -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", diff --git a/src/Concerns/ManagesInvoices.php b/src/Concerns/ManagesInvoices.php index 11bca100..b08570b3 100644 --- a/src/Concerns/ManagesInvoices.php +++ b/src/Concerns/ManagesInvoices.php @@ -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; @@ -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'], + ])); + } }