Completed
Push — master ( 037c01...3910ea )
by Oscar
01:42
created

HasPagination   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 45
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A page() 0 7 1
A perPage() 0 7 1
A getPageInfo() 0 23 4
1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud\Queries\Traits;
5
6
use PDO;
7
8
trait HasPagination
9
{
10
    private $page;
11
    private $perPage = 10;
12
13
    public function page(int $page): self
14
    {
15
        $this->page = $page;
16
        $this->query->page($page);
0 ignored issues
show
Bug introduced by
The property query 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...
17
18
        return $this;
19
    }
20
21
    public function perPage(int $perPage = 10): self
22
    {
23
        $this->perPage = $perPage;
24
        $this->query->perPage($perPage);
25
26
        return $this;
27
    }
28
29
    public function getPageInfo()
30
    {
31
        $query = clone $this->query;
32
        $query->resetOrderBy();
33
        $query->resetLimit();
34
        $query->resetColumns();
35
        $query->columns('COUNT(*)');
36
37
        $statement = $query->perform();
38
        $statement->setFetchMode(PDO::FETCH_NUM);
39
40
        $page = $this->page;
41
        $count = $statement->fetch();
42
        $count = intval($count[0]);
43
44
        return [
45
            'totalRows' => $count,
46
            'totalPages' => (int) ceil($count / $this->perPage),
47
            'currentPage' => $count ? $page : null,
48
            'previousPage' => $page > 1 ? $page - 1 : null,
49
            'nextPage' => $count > ($page * $this->perPage) ? $page + 1 : null,
50
        ];
51
    }
52
}
53