| 1: | <?php declare(strict_types=1); |
| 2: | |
| 3: | namespace Salient\Curler\Pager; |
| 4: | |
| 5: | use Psr\Http\Message\RequestInterface as PsrRequestInterface; |
| 6: | use Salient\Contract\Curler\CurlerInterface; |
| 7: | use Salient\Contract\Curler\CurlerPageInterface; |
| 8: | use Salient\Contract\Curler\CurlerPagerInterface; |
| 9: | use Salient\Contract\Http\Message\ResponseInterface; |
| 10: | use Salient\Curler\CurlerPage; |
| 11: | use Salient\Curler\CurlerPageRequest; |
| 12: | use Salient\Http\HttpUtil; |
| 13: | use Salient\Http\Uri; |
| 14: | use Closure; |
| 15: | |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | final class LinkPager implements CurlerPagerInterface |
| 22: | { |
| 23: | use HasEntitySelector; |
| 24: | |
| 25: | private ?int $PageSize; |
| 26: | private string $PageSizeKey; |
| 27: | |
| 28: | |
| 29: | |
| 30: | |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | |
| 36: | |
| 37: | |
| 38: | public function __construct( |
| 39: | ?int $pageSize = null, |
| 40: | $entitySelector = null, |
| 41: | string $pageSizeKey = 'per_page' |
| 42: | ) { |
| 43: | $this->PageSize = $pageSize; |
| 44: | if ($pageSize !== null) { |
| 45: | $this->PageSizeKey = $pageSizeKey; |
| 46: | } |
| 47: | $this->applyEntitySelector($entitySelector); |
| 48: | } |
| 49: | |
| 50: | |
| 51: | |
| 52: | |
| 53: | public function getFirstRequest( |
| 54: | PsrRequestInterface $request, |
| 55: | CurlerInterface $curler, |
| 56: | ?array $query = null |
| 57: | ) { |
| 58: | if ($this->PageSize === null) { |
| 59: | return $request; |
| 60: | } |
| 61: | |
| 62: | $query[$this->PageSizeKey] = $this->PageSize; |
| 63: | return new CurlerPageRequest( |
| 64: | $curler->replaceQuery($request, $query), |
| 65: | $query, |
| 66: | ); |
| 67: | } |
| 68: | |
| 69: | |
| 70: | |
| 71: | |
| 72: | public function getPage( |
| 73: | $data, |
| 74: | PsrRequestInterface $request, |
| 75: | ResponseInterface $response, |
| 76: | CurlerInterface $curler, |
| 77: | ?CurlerPageInterface $previousPage = null, |
| 78: | ?int $previousEntities = null, |
| 79: | ?array $query = null |
| 80: | ): CurlerPageInterface { |
| 81: | $data = ($this->EntitySelector)($data); |
| 82: | |
| 83: | foreach ($response->getHeaderValues(self::HEADER_LINK) as $link) { |
| 84: | |
| 85: | $link = HttpUtil::getParameters($link); |
| 86: | if (($link['rel'] ?? null) === 'next') { |
| 87: | $link = trim($link[0], '<>'); |
| 88: | $uri = $request->getUri(); |
| 89: | $uri = Uri::from($uri)->follow($link); |
| 90: | $nextRequest = $request->withUri($uri); |
| 91: | break; |
| 92: | } |
| 93: | } |
| 94: | |
| 95: | return new CurlerPage($data, $nextRequest ?? null); |
| 96: | } |
| 97: | } |
| 98: | |