|
16 | 16 | */
|
17 | 17 | class StoryApi extends EndpointSpace
|
18 | 18 | {
|
| 19 | + public function all(): \Generator |
| 20 | + { |
| 21 | + $pageNumber = 1; |
| 22 | + $itemsPerPage = 5; |
| 23 | + $totalPages = null; |
| 24 | + |
| 25 | + do { |
| 26 | + |
| 27 | + // Fetch the current page |
| 28 | + $response = $this->page($pageNumber, $itemsPerPage); |
| 29 | + |
| 30 | + if ($response->isOk()) { |
| 31 | + // Print the total number of tags (only on the first iteration) |
| 32 | + if ($totalPages === null) { |
| 33 | + //echo "Total Stories: " . $response->total() . PHP_EOL; |
| 34 | + // Calculate the total number of pages |
| 35 | + $totalPages = ceil($response->total() / $itemsPerPage); |
| 36 | + } |
| 37 | + |
| 38 | + /** @var StoriesData $stories */ |
| 39 | + $stories = $response->data(); |
| 40 | + foreach ($stories as $story) { |
| 41 | + yield $story; |
| 42 | + } |
| 43 | + |
| 44 | + // Move to the next page |
| 45 | + ++$pageNumber; |
| 46 | + } elseif ($response->getResponseStatusCode() === 429) { |
| 47 | + echo "Rate limit reached. Retrying in 1 second..." . PHP_EOL; |
| 48 | + sleep(1); |
| 49 | + // Wait for 1 second before retrying |
| 50 | + } else { |
| 51 | + // Handle other exceptions |
| 52 | + echo "An error occurred: " . $response->getErrorMessage() . PHP_EOL; |
| 53 | + break; // Exit the loop on non-recoverable errors |
| 54 | + } |
| 55 | + |
| 56 | + } while ($pageNumber <= $totalPages); |
| 57 | + } |
| 58 | + |
19 | 59 | public function page(int $page = 1, int $perPage = 25): StoryblokResponseInterface
|
20 | 60 | {
|
| 61 | + $options = [ |
| 62 | + 'query' => [ |
| 63 | + 'page' => $page, |
| 64 | + 'per_page' => $perPage, |
| 65 | + ], |
| 66 | + ]; |
21 | 67 | return $this->makeRequest(
|
22 | 68 | "GET",
|
23 | 69 | '/v1/spaces/' . $this->spaceId . '/stories',
|
| 70 | + options: $options, |
24 | 71 | dataClass: StoriesData::class,
|
25 | 72 | );
|
26 | 73 | }
|
|
0 commit comments