Completed
Pull Request — master (#19)
by Daniel
03:21 queued 01:29
created

Paginator::getNumberOfPages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid;
6
7
class Paginator
8
{
9
    private $options;
10
    private $numberOfRecords;
11
    private $numberOfRecordsOnPage;
12
13
    public function __construct(GridContext $options, int $numberOfRecordsOnPage, int $numberOfRecords = null)
14
    {
15
        $this->options = $options;
16
        $this->numberOfRecords = $numberOfRecords;
17
        $this->numberOfRecordsOnPage = $numberOfRecordsOnPage;
18
    }
19
20
    public function getPageSize(): int
21
    {
22
        return $this->options->getPageSize();
23
    }
24
25
    public function getCurrentPage(): int
26
    {
27
        return $this->options->getCurrentPage();
28
    }
29
30
    public function getNumberOfRecords()
31
    {
32
        return $this->numberOfRecords;
33
    }
34
35
    public function getNumberOfPages(): int
36
    {
37
        if (null === $this->numberOfRecords) {
38
            throw new \RuntimeException(
39
                'Cannot determine the last page when the total number of ' .
40
                'records has not been provided.'
41
            );
42
        }
43
44
        return (int) ceil($this->getNumberOfRecords() / $this->getPageSize());
45
    }
46
47
    public function isLastPage(): bool
48
    {
49
        if (null === $this->numberOfRecords) {
50
            return $this->numberOfRecordsOnPage < $this->getPageSize();
51
        }
52
53
        return $this->getCurrentPage() == $this->getNumberOfPages();
54
    }
55
56
    public function getUrlParametersForPage($page = null)
57
    {
58
        return array_merge($this->options->getUrlParameters(), [
59
            'page' => $page ?: $this->options->getCurrentPage(),
60
        ]);
61
    }
62
}
63