1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace API\Helpers; |
4
|
|
|
|
5
|
|
|
class Paginator |
6
|
|
|
{ |
7
|
|
|
private $config; |
8
|
|
|
private $countQuery; |
9
|
|
|
private $paginationQuery; |
10
|
|
|
private $totalItems; |
11
|
|
|
private $totalPages; |
12
|
|
|
|
13
|
|
|
public function __construct($query, $config, $db) |
14
|
|
|
{ |
15
|
|
|
$this->config = $config; |
16
|
|
|
$this->craftQuries($query); |
17
|
|
|
$this->performQueries($db); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* create two queries out of the given query : |
22
|
|
|
* - query to count the rows |
23
|
|
|
* - query to paginate the data. |
24
|
|
|
* |
25
|
|
|
* @todo handle the case when the query already have the limit clause. |
26
|
|
|
*/ |
27
|
|
|
public function craftQuries($query) |
28
|
|
|
{ |
29
|
|
|
|
30
|
|
|
// replace the columns part with count(*) as total to number of rows |
31
|
|
|
$this->countQuery = preg_replace('/(select ).*( from.*)/i', '$1 count(*) as total $2', $query); |
32
|
|
|
|
33
|
|
|
$startFrom = ($this->config['current_page'] * $this->config['item_per_page']) - $this->config['item_per_page']; |
34
|
|
|
$this->paginationQuery = $query.' limit '.$startFrom.', '.$this->config['item_per_page']; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function performQueries($db) |
38
|
|
|
{ |
39
|
|
|
$this->totalItems = $db->query($this->countQuery)->fetch()['total']; |
40
|
|
|
$this->totalPages = ceil($this->totalItems / $this->config['item_per_page']); |
41
|
|
|
$this->currentItems = $db->query($this->paginationQuery)->fetchAll(); |
|
|
|
|
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function getCurrentItems() |
45
|
|
|
{ |
46
|
|
|
return $this->currentItems; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getCurrentPage() |
50
|
|
|
{ |
51
|
|
|
return $this->config['current_page']; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getTotalItem() |
55
|
|
|
{ |
56
|
|
|
return $this->totalItems; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getRowsPerPage() |
60
|
|
|
{ |
61
|
|
|
return $this->config['item_per_page']; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function getTotalPages() |
65
|
|
|
{ |
66
|
|
|
return $this->totalPages; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: