Skip to content

Commit b238541

Browse files
authored
Merge pull request #32 from tareq-halaby/tareq-halaby-patch-6
Add Paginator class for SQL query pagination
2 parents 35eba68 + 3683663 commit b238541

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

src/Paginator.php

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SqlPowertools;
6+
7+
/**
8+
* Paginator - SQL Query Pagination Helper
9+
*
10+
* Wraps a QueryBuilder instance to provide cursor-based and
11+
* offset-based pagination with metadata.
12+
*
13+
* @package SqlPowertools
14+
* @version 1.3.0
15+
*/
16+
class Paginator
17+
{
18+
private int $total = 0;
19+
private array $items = [];
20+
21+
public function __construct(
22+
private readonly QueryBuilder $query,
23+
private readonly int $perPage = 15,
24+
private readonly int $currentPage = 1
25+
) {}
26+
27+
/**
28+
* Execute pagination and return results with metadata.
29+
*/
30+
public function paginate(): array
31+
{
32+
$offset = ($this->currentPage - 1) * $this->perPage;
33+
$this->items = $this->query->limit($this->perPage)->offset($offset)->get();
34+
return [
35+
'data' => $this->items,
36+
'meta' => $this->getMeta(),
37+
];
38+
}
39+
40+
/**
41+
* Get pagination metadata.
42+
*/
43+
public function getMeta(): array
44+
{
45+
return [
46+
'current_page' => $this->currentPage,
47+
'per_page' => $this->perPage,
48+
'has_next' => count($this->items) === $this->perPage,
49+
'has_previous' => $this->currentPage > 1,
50+
];
51+
}
52+
53+
/**
54+
* Check if there is a next page.
55+
*/
56+
public function hasNextPage(): bool
57+
{
58+
return count($this->items) === $this->perPage;
59+
}
60+
61+
/**
62+
* Get the next page number.
63+
*/
64+
public function nextPage(): int
65+
{
66+
return $this->currentPage + 1;
67+
}
68+
69+
/**
70+
* Get the previous page number.
71+
*/
72+
public function previousPage(): int
73+
{
74+
return max(1, $this->currentPage - 1);
75+
}
76+
}

0 commit comments

Comments
 (0)