Skip to content

Commit

Permalink
listAll method to list all resources
Browse files Browse the repository at this point in the history
  • Loading branch information
Baspa committed Aug 25, 2023
1 parent e5e3809 commit a5c7892
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/Resources/Resource.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,57 @@ public function list(array $params = []): array
);
}

/**
* @param int $offset
* @param int $perPage
* @return array<string, mixed>|MethodNotAvailableException|ClientException|ServerException|BadResponseException|JsonException
*
* @throws ClientException|ServerException|BadResponseException|JsonException
*/
public function listAll(int $offset = 0, int $perPage = 1000)
{
// Rate limit the requests to prevent IP blocking.
$limitPerSecond = 300 / 60; // Per minute / seconds
$calls = 1;

$data = [];

// TODO: This is a hacky way to get the plural resource name.
$pluralResourceName = $this->getResourceName() . 's';

$result = $this->sendRequest(
controller: $this->getResourceName(),
action: Action::LIST->value,
params: [
'limit' => $perPage,
'offset' => $offset,
]
);

foreach($result[$pluralResourceName] as $index => $item) {
$calls++;

if ($calls % $limitPerSecond == 0) {
sleep(1);
}

$resultItem = $this->show([
'Identifier' => $item['Identifier'],
]);

$result[$pluralResourceName][$index] = $resultItem[$pluralResourceName];

Check failure on line 81 in src/Resources/Resource.php

View workflow job for this annotation

GitHub Actions / phpstan

Cannot access offset non-falsy-string on array<string, mixed>|GuzzleHttp\Exception\BadResponseException|JsonException|Vormkracht10\WeFact\Exceptions\MethodNotAvailableException.
}

$data = array_merge($data, $result[$pluralResourceName] ?? []);

if ($result['currentresults'] >= $perPage) {
$offset += $perPage;
$data = array_merge($data, $this->listAll($offset, $perPage));

Check failure on line 88 in src/Resources/Resource.php

View workflow job for this annotation

GitHub Actions / phpstan

Parameter #2 ...$arrays of function array_merge expects array, array<string, mixed>|GuzzleHttp\Exception\BadResponseException|JsonException|Vormkracht10\WeFact\Exceptions\MethodNotAvailableException given.
}

return $data;
}

/**
* @param array<string, mixed> $params
* @return array<string, mixed>|MethodNotAvailableException|ClientException|ServerException|BadResponseException|JsonException
Expand Down

0 comments on commit a5c7892

Please sign in to comment.