Completed
Branch 7-dev (bf2895)
by Oscar
03:53
created

HasPagination::getPageInfo()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 3
nc 4
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud\Query\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
            'total' => $count,
46
            'page' => $page,
47
            'previous' => $page > 1 ? $page - 1 : null,
48
            'next' => $count > ($page * $this->perPage) ? $page + 1 : null,
49
        ];
50
    }
51
}
52