dzava/resource-iterator

v1.3.0 2021-11-09 16:47 UTC

This package is auto-updated.

Last update: 2024-09-09 22:59:48 UTC


README

本包为遍历分页 JSON API 的基础提供支持。

安装

您可以通过 composer 安装此包。

composer require dzava/resource-iterator

用法

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();

使用 withConfig 方法覆盖默认配置。

[
    '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
]

自定义迭代器

要创建自定义迭代器,只需扩展 ResourceIterator 类并实现 nextPage 方法。该方法应返回指向下一页的 page 查询参数的值,或在没有更多页时返回 false。如果下一页的 URL 更复杂,您可以覆盖 nextPageUrl 方法并返回下一页的完整 URL 或 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";
}

许可证

MIT 许可证 (MIT)