Skip to content

Commit 0ed18c2

Browse files
committed
Introducing all() method
1 parent 2fb815a commit 0ed18c2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/Endpoints/StoryApi.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,58 @@
1616
*/
1717
class StoryApi extends EndpointSpace
1818
{
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+
1959
public function page(int $page = 1, int $perPage = 25): StoryblokResponseInterface
2060
{
61+
$options = [
62+
'query' => [
63+
'page' => $page,
64+
'per_page' => $perPage,
65+
],
66+
];
2167
return $this->makeRequest(
2268
"GET",
2369
'/v1/spaces/' . $this->spaceId . '/stories',
70+
options: $options,
2471
dataClass: StoriesData::class,
2572
);
2673
}

0 commit comments

Comments
 (0)