Skip to content

Instantly share code, notes, and snippets.

@neverything
Created December 9, 2023 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neverything/a7953490c2ebe87035c4cf7e4e0acbb7 to your computer and use it in GitHub Desktop.
Save neverything/a7953490c2ebe87035c4cf7e4e0acbb7 to your computer and use it in GitHub Desktop.
<?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