Skip to content

Commit

Permalink
Merge pull request #53 from picqer/pagination
Browse files Browse the repository at this point in the history
Add pagination to FindAll trait
  • Loading branch information
casperbakker authored Dec 10, 2024
2 parents 4a8e063 + a4d4a39 commit d2de7b5
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 10 deletions.
32 changes: 26 additions & 6 deletions src/Picqer/Carriers/SendCloud/Query/FindAll.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,36 @@
*/
trait FindAll
{

public function all($params = [])
public function all($params = [], ?int $maxPages = 1): array
{
$result = $this->connection()->get($this->url, $params);
$allRecords = [];
$pages = 0;

while (true) {
$result = $this->connection()->get($this->url, $params);

$allRecords = array_merge($allRecords, $this->collectionFromResult($result));

if (! empty($result['next'])) {
// Get the querystring params from the next url, so we can retrieve the next page
$params = parse_url($result['next'], PHP_URL_QUERY);
} else {
// If no next page is found, all records are complete
break;
}

return $this->collectionFromResult($result);
$pages++;

// If max pages is set and reached, also stop the loop
if (! is_null($maxPages) && $pages >= $maxPages) {
break;
}
}

return $allRecords;
}

public function collectionFromResult($result)
public function collectionFromResult($result): array
{
$collection = [];

Expand All @@ -36,5 +57,4 @@ public function collectionFromResult($result)

return $collection;
}

}
3 changes: 2 additions & 1 deletion src/Picqer/Carriers/SendCloud/Query/FindOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Picqer\Carriers\SendCloud\Connection;
use Picqer\Carriers\SendCloud\Model;
use Picqer\Carriers\SendCloud\SendCloudApiException;

/**
* Trait FindOne
Expand All @@ -14,10 +15,10 @@
*/
trait FindOne
{

/**
* @param $id
* @return Model|FindOne
* @throws SendCloudApiException
*/
public function find($id)
{
Expand Down
4 changes: 1 addition & 3 deletions src/Picqer/Carriers/SendCloud/Query/Findable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

trait Findable
{

use FindOne;
use FindAll;

}
}

0 comments on commit d2de7b5

Please sign in to comment.