Created
December 9, 2023 09:01
-
-
Save neverything/a7953490c2ebe87035c4cf7e4e0acbb7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Custom HasPagination interface | |
namespace App\Http\Integrations\GithubApi\Contracts; | |
use Saloon\Http\Request; | |
use Saloon\PaginationPlugin\Paginator; | |
interface HasPagination | |
{ | |
public function paginate(Request $request, int $totalItems): Paginator; | |
} | |
// Connector | |
namespace App\Http\Integrations\GithubApi; | |
use App\Http\Integrations\GithubApi\Contracts\HasPagination; | |
// ... | |
class GithubApiConnector extends Connector implements HasPagination | |
{ | |
// ... | |
public function paginate(Request $request, int $totalItems): PagedPaginator | |
{ | |
return new class(connector: $this, request: $request, totalItems: $totalItems) extends PagedPaginator | |
{ | |
protected ?int $perPageLimit = 100; | |
protected int $receivedItems = 0; | |
public function __construct( | |
protected Connector $connector, | |
protected Request $request, | |
protected int $totalItems | |
) { | |
parent::__construct($connector, $request); | |
} | |
protected function isLastPage(Response $response): bool | |
{ | |
$this->receivedItems += count($response->json('items')); | |
return $this->receivedItems >= $this->totalItems; | |
} | |
protected function getPageItems(Response $response, Request $request): array | |
{ | |
$items = $response->json('items'); | |
if ($this->receivedItems + count($items) > $this->totalItems) { | |
$items = array_slice($items, 0, $this->totalItems - $this->receivedItems); | |
} | |
return $items; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment