Skip to content

Commit a08af97

Browse files
authored
Merge pull request #41 from bufferapp/support-batch-total-values
Support batch calls for total value metrics
2 parents 998d49a + 4e51e47 commit a08af97

File tree

3 files changed

+454
-157
lines changed

3 files changed

+454
-157
lines changed

Facebook/Facebook.php

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,8 @@ public function getPageInsightsMetricsData($pageId, $insightsMetrics, $since, $u
8282
$intervals = $this->getIntervalsForPeriod($since, $until);
8383

8484
foreach ($intervals as $interval) {
85-
$params["since"] = $interval['since'];
86-
$params["until"] = $interval['until'];
85+
$params["since"] = $interval["since"];
86+
$params["until"] = $interval["until"];
8787
$requests[] = $this->createRequest("GET", "/{$pageId}/insights", $params);
8888
}
8989

@@ -168,6 +168,56 @@ public function getPageInsightsForTotalValueMetrics($pageId, $metrics, $period,
168168
return $data;
169169
}
170170

171+
/*
172+
* Get page insights for total value metrics in batch for multiple date ranges
173+
*/
174+
public function getPageInsightsBatchTotalValueMetrics($pageId, $metrics, $period, $days)
175+
{
176+
$result = [];
177+
$metricsString = join(",", $metrics);
178+
$batchSize = 50; // Facebook's batch request limit
179+
180+
// Process days in chunks of 50
181+
$dayChunks = array_chunk($days, $batchSize);
182+
183+
foreach ($dayChunks as $chunk) {
184+
$batchRequests = [];
185+
186+
// Create a batch request for each date range in this chunk
187+
foreach ($chunk as $day) {
188+
$params = [
189+
"metric" => $metricsString,
190+
"metric_type" => "total_value",
191+
"period" => $period,
192+
"since" => $day["since"],
193+
"until" => $day["until"],
194+
];
195+
196+
$request = $this->createRequest("GET", "/{$pageId}/insights", $params);
197+
$batchRequests[$day["since"]] = $request;
198+
}
199+
200+
// Send this batch of requests
201+
$responses = $this->sendBatchRequest($batchRequests);
202+
if (!empty($responses)) {
203+
foreach ($responses as $timestamp => $response) {
204+
$decodedBody = $response->getDecodedBody();
205+
206+
if (!empty($decodedBody) && is_array($decodedBody)) {
207+
$responseData = $decodedBody["data"];
208+
$data = [];
209+
foreach ($responseData as $metric) {
210+
$data[$metric["name"]] = $metric["total_value"]["value"];
211+
}
212+
$result[$timestamp] = $data;
213+
}
214+
}
215+
}
216+
}
217+
218+
return $result;
219+
}
220+
171221
/*
172222
* Get Instagram Graph node metadata
173223
*/

0 commit comments

Comments
 (0)