dzava / resource-iterator
v1.3.0
2021-11-09 16:47 UTC
Requires
- php: ^7.4|^8.0
- ext-json: *
- guzzlehttp/guzzle: ^6.3|^7.0
- illuminate/support: ^7.0|^8.0
Requires (Dev)
- larapack/dd: ^1.0
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2025-04-10 00:12:23 UTC
README
This package provides the foundation for iterating over paginated json apis.
Installation
You can install the package via composer:
composer require dzava/resource-iterator
Usage
use Dzava\ResourceIterator\PagedResourceIterator; // Given a response with the following structure // { // "total_pages": 4, // "data": [] // } $users = (new PagedResourceIterator('https://example.com/api/users/'))->toArray(); // Given a response with the following structure // { // "pagination: { // "total_pages": 4, // } // "data": [] // } $users = (new PagedResourceIterator('https://example.com/api/users/')) ->withConfig(['totalPages' => 'pagination.total_pages']) ->toArray();
Use the withConfig
method to override the default configuration.
[ 'page' => 'page', // name of the query param that indicates the current page 'data' => 'data', // the response field that contains the data 'totalPages' => 'total_pages' // the response field that contains the total number of pages ]
Custom iterators
To create a custom iterator simply extend the ResourceIterator
class and implement the nextPage
method.
The method should return the value of the page
query parameter that points to the next page or false
when there are no more pages.
If the url for the next page is more complex you can override the nextPageUrl
method and return the complete url for the next page or false
.
use Dzava\ResourceIterator\ResourceIterator; class GithubResourceIterator extends ResourceIterator { public function __construct($url) { parent::__construct($url); $this->withConfig(['data' => null]); } protected function nextPageUrl() { preg_match('/<(.*?)>.*?rel="next"/', $this->lastResponse->getHeader('Link')[0], $matches); return $matches[1] ?? false; } } $iterator = new GithubResourceIterator('https://api.github.com/orgs/laravel/repos'); foreach ($iterator->items() as $repo) { echo "{$repo->full_name}\n"; }
License
The MIT License (MIT).