1 | <?php |
||
2 | |||
3 | namespace NavigaAdClient\Responses; |
||
4 | |||
5 | use Illuminate\Http\Client\Response; |
||
6 | use NavigaAdClient\Requests\PaginatedRequest; |
||
7 | |||
8 | class PaginatedResponse extends Response |
||
9 | { |
||
10 | protected PaginatedRequest $request; |
||
11 | protected array $query = []; |
||
12 | |||
13 | 1 | public function __construct($response, PaginatedRequest $request, array $query = []) |
|
14 | { |
||
15 | 1 | parent::__construct($response); |
|
16 | 1 | $this->request = $request; |
|
17 | 1 | $this->query = $query; |
|
18 | } |
||
19 | |||
20 | 1 | public function entities(?string $class = null): array |
|
21 | { |
||
22 | 1 | $items = $this->json('Results'); |
|
23 | 1 | if (!is_array($items)) { |
|
24 | return []; |
||
25 | } |
||
26 | 1 | if ($class) { |
|
27 | $items = array_map(fn ($item) => new $class($item), $items); |
||
28 | } |
||
29 | |||
30 | 1 | return $items; |
|
31 | } |
||
32 | |||
33 | 1 | public function currentPage(): int |
|
34 | { |
||
35 | 1 | return (int ) $this->json('PageNumber'); |
|
36 | } |
||
37 | |||
38 | 1 | public function countEntities(): int |
|
39 | { |
||
40 | 1 | return (int ) $this->json('PageSize'); |
|
41 | } |
||
42 | |||
43 | 1 | public function isEmpty(): bool |
|
44 | { |
||
45 | 1 | return $this->json('PageSize') <= 0; |
|
46 | } |
||
47 | |||
48 | 1 | public function totalPages(): int |
|
49 | { |
||
50 | 1 | return (int ) $this->json('TotalNumberOfPages'); |
|
51 | } |
||
52 | |||
53 | 1 | public function totalEntities(): int |
|
54 | { |
||
55 | 1 | return (int ) $this->json('TotalNumberOfRecords'); |
|
56 | } |
||
57 | |||
58 | 1 | public function hasNext(): bool |
|
59 | { |
||
60 | 1 | return $this->currentPage() < $this->totalPages(); |
|
61 | } |
||
62 | |||
63 | 1 | public function hasPrev(): bool |
|
64 | { |
||
65 | 1 | return $this->currentPage() > 1; |
|
66 | } |
||
67 | |||
68 | 1 | public function nextPage(): ?static |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
69 | { |
||
70 | 1 | if (!$this->hasNext()) { |
|
71 | 1 | return null; |
|
72 | } |
||
73 | |||
74 | 1 | return $this->request->setCurrentPage($this->currentPage() + 1)->retrieve($this->query); |
|
75 | } |
||
76 | |||
77 | 1 | public function prevPage(): ?static |
|
78 | { |
||
79 | 1 | if (!$this->hasPrev()) { |
|
80 | 1 | return null; |
|
81 | } |
||
82 | |||
83 | 1 | return $this->request->setCurrentPage($this->currentPage() + 1)->retrieve($this->query); |
|
84 | } |
||
85 | } |
||
86 |