Skip to content

Instantly share code, notes, and snippets.

@frankdejonge
Created May 25, 2021 18:12
Show Gist options
  • Select an option

  • Save frankdejonge/b81fa02c82d69d0bb39b3f9fce81225c to your computer and use it in GitHub Desktop.

Select an option

Save frankdejonge/b81fa02c82d69d0bb39b3f9fce81225c to your computer and use it in GitHub Desktop.

Revisions

  1. frankdejonge created this gist May 25, 2021.
    28 changes: 28 additions & 0 deletions paginated-generator.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    <?php

    /**
    * Imagine this is an API call
    */
    function listPage(int $i): array
    {
    $next = $i >= 9 ? null : $i + 1;
    return ['cursor' => $next, 'items' => array_fill(0, 5, $i)];
    }

    function listPagedResponse(): Generator
    {
    $i = 0;
    do {
    $response = listPage($i);
    foreach ($response['items'] as $item) {
    yield $item;
    }
    } while ($i = $response['cursor']);
    }

    /**
    * The consumer is not aware we're doing multiple API calls
    */
    foreach (listPagedResponse() as $item) {
    var_dump($item);
    }