Paginator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A craftQuries() 0 9 1
A performQueries() 0 6 1
A getCurrentItems() 0 4 1
A getCurrentPage() 0 4 1
A getTotalItem() 0 4 1
A getRowsPerPage() 0 4 1
A getTotalPages() 0 4 1
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();
0 ignored issues
show
Bug introduced by
The property currentItems does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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