Skip to content

Commit 86ae215

Browse files
committed
use total_count from redmine response to avoid unnecessary http requests
1 parent 0593716 commit 86ae215

File tree

1 file changed

+32
-14
lines changed

1 file changed

+32
-14
lines changed

src/Redmine/Api/AbstractApi.php

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -320,18 +320,18 @@ protected function retrieveData(string $endpoint, array $params = []): array
320320

321321
$returnData = [];
322322

323-
$limit = $params['limit'];
323+
$requestedLimit = $remaininglimit = $params['limit'];
324324
$offset = $params['offset'];
325325

326-
while ($limit > 0) {
327-
if ($limit > 100) {
328-
$_limit = 100;
329-
$limit -= 100;
326+
while ($remaininglimit > 0) {
327+
if ($remaininglimit > 100) {
328+
$realLimit = 100;
329+
$remaininglimit -= 100;
330330
} else {
331-
$_limit = $limit;
332-
$limit = 0;
331+
$realLimit = $remaininglimit;
332+
$remaininglimit = 0;
333333
}
334-
$params['limit'] = $_limit;
334+
$params['limit'] = $realLimit;
335335
$params['offset'] = $offset;
336336

337337
$this->lastResponse = $this->getHttpClient()->request(HttpFactory::makeRequest(
@@ -344,16 +344,34 @@ protected function retrieveData(string $endpoint, array $params = []): array
344344

345345
$returnData = array_merge_recursive($returnData, $newDataSet);
346346

347-
$offset += $_limit;
347+
// After the first request we know the total_count for this endpoint
348+
// so lets use the total_count to correct $requestedLimit to save us
349+
// from making unnecessary requests
350+
// e.g. total_count = 5; $requestedLimit = 500 will make only 1 request instead of 5
351+
if (isset($newDataSet['total_count']) && $newDataSet['total_count'] < $requestedLimit) {
352+
$requestedLimit = $remaininglimit = (int) $newDataSet['total_count'];
353+
354+
if ($remaininglimit > 100) {
355+
$realLimit = 100;
356+
$remaininglimit -= 100;
357+
} else {
358+
$realLimit = $remaininglimit;
359+
$remaininglimit = 0;
360+
}
361+
}
362+
363+
$offset += $realLimit;
348364

349365
if (
350-
empty($newDataSet) || !isset($newDataSet['limit']) || (
351-
isset($newDataSet['offset']) &&
352-
isset($newDataSet['total_count']) &&
353-
$newDataSet['offset'] >= $newDataSet['total_count']
366+
empty($newDataSet)
367+
|| !isset($newDataSet['limit'])
368+
|| (
369+
isset($newDataSet['offset'])
370+
&& isset($newDataSet['total_count'])
371+
&& $newDataSet['offset'] >= $newDataSet['total_count']
354372
)
355373
) {
356-
$limit = 0;
374+
$remaininglimit = 0;
357375
}
358376
}
359377

0 commit comments

Comments
 (0)