Skip to content

Commit d2de7b5

Browse files
authored
Merge pull request #53 from picqer/pagination
Add pagination to FindAll trait
2 parents 4a8e063 + a4d4a39 commit d2de7b5

File tree

3 files changed

+29
-10
lines changed

3 files changed

+29
-10
lines changed

src/Picqer/Carriers/SendCloud/Query/FindAll.php

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,36 @@
1313
*/
1414
trait FindAll
1515
{
16-
17-
public function all($params = [])
16+
public function all($params = [], ?int $maxPages = 1): array
1817
{
19-
$result = $this->connection()->get($this->url, $params);
18+
$allRecords = [];
19+
$pages = 0;
20+
21+
while (true) {
22+
$result = $this->connection()->get($this->url, $params);
23+
24+
$allRecords = array_merge($allRecords, $this->collectionFromResult($result));
25+
26+
if (! empty($result['next'])) {
27+
// Get the querystring params from the next url, so we can retrieve the next page
28+
$params = parse_url($result['next'], PHP_URL_QUERY);
29+
} else {
30+
// If no next page is found, all records are complete
31+
break;
32+
}
2033

21-
return $this->collectionFromResult($result);
34+
$pages++;
35+
36+
// If max pages is set and reached, also stop the loop
37+
if (! is_null($maxPages) && $pages >= $maxPages) {
38+
break;
39+
}
40+
}
41+
42+
return $allRecords;
2243
}
2344

24-
public function collectionFromResult($result)
45+
public function collectionFromResult($result): array
2546
{
2647
$collection = [];
2748

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

3758
return $collection;
3859
}
39-
4060
}

src/Picqer/Carriers/SendCloud/Query/FindOne.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Picqer\Carriers\SendCloud\Connection;
66
use Picqer\Carriers\SendCloud\Model;
7+
use Picqer\Carriers\SendCloud\SendCloudApiException;
78

89
/**
910
* Trait FindOne
@@ -14,10 +15,10 @@
1415
*/
1516
trait FindOne
1617
{
17-
1818
/**
1919
* @param $id
2020
* @return Model|FindOne
21+
* @throws SendCloudApiException
2122
*/
2223
public function find($id)
2324
{

src/Picqer/Carriers/SendCloud/Query/Findable.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44

55
trait Findable
66
{
7-
87
use FindOne;
98
use FindAll;
10-
11-
}
9+
}

0 commit comments

Comments
 (0)