Completed
Push — master ( f11337...38bba2 )
by Kevin
02:15
created

ResultPager::getLimit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Zenstruck\Porpaginas\Pager;
4
5
use Zenstruck\Porpaginas\Pager;
6
use Zenstruck\Porpaginas\Result;
7
8
/**
9
 * @author Kevin Bond <[email protected]>
10
 */
11
final class ResultPager extends Pager
12
{
13
    const DEFAULT_LIMIT = 20;
14
15
    private $result;
16
    private $page;
17
    private $limit;
18
    private $cachedPage;
19
20
    /**
21
     * @param Result $result
22
     * @param int    $page
23
     * @param int    $limit
24
     */
25 8
    public function __construct(Result $result, $page = 1, $limit = self::DEFAULT_LIMIT)
26
    {
27 8
        if (!is_numeric($page)) {
28 1
            $page = 1;
29 1
        }
30
31 8
        if (!is_numeric($limit)) {
32 1
            $limit = self::DEFAULT_LIMIT;
33 1
        }
34
35 8
        $page = (int) $page;
36 8
        $limit = (int) $limit;
37
38 8
        if ($page < 1) {
39 1
            $page = 1;
40 1
        }
41
42 8
        if ($limit < 1) {
43 1
            $limit = 1;
44 1
        }
45
46 8
        $this->result = $result;
47 8
        $this->page = $page;
48 8
        $this->limit = $limit;
49 8
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 7
    public function getCurrentPage()
55
    {
56 7
        $lastPage = $this->getLastPage();
57
58 7
        if ($this->page > $lastPage) {
59 1
            return $lastPage;
60
        }
61
62 6
        return $this->page;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 7
    public function getLimit()
69
    {
70 7
        return $this->limit;
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 6
    public function count()
77
    {
78 6
        return $this->getResults()->count();
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84 7
    public function totalCount()
85
    {
86 7
        return $this->result->count();
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92 6
    public function getResults()
93
    {
94 6
        if ($this->cachedPage !== null) {
95 6
            return $this->cachedPage;
96
        }
97
98 6
        $offset = $this->getCurrentPage() * $this->getLimit() - $this->getLimit();
99
100 6
        return $this->cachedPage = $this->result->take($offset, $this->getLimit());
101
    }
102
}
103