Completed
Push — master ( 0a4f4d...d259d9 )
by Kevin
02:17
created

CallbackPage::totalCount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2.0625
1
<?php
2
3
namespace Zenstruck\Porpaginas\Callback;
4
5
use Zenstruck\Porpaginas\Page;
6
7
/**
8
 * @author Kevin Bond <[email protected]>
9
 */
10
final class CallbackPage implements Page
11
{
12
    private $resultCallback;
13
    private $totalCountCallback;
14
    private $offset;
15
    private $limit;
16
    private $totalCount;
17
    private $results;
18
19
    /**
20
     * @param callable $resultCallback     Returns an array
21
     * @param callable $totalCountCallback Returns an integer
22
     * @param int      $offset
23
     * @param int      $limit
24
     */
25 16
    public function __construct(callable $resultCallback, callable $totalCountCallback, $offset, $limit)
26
    {
27 16
        $this->resultCallback = $resultCallback;
28 16
        $this->totalCountCallback = $totalCountCallback;
29 16
        $this->offset = $offset;
30 16
        $this->limit = $limit;
31 16
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 8
    public function getCurrentOffset()
37
    {
38 8
        return $this->offset;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 8
    public function getCurrentPage()
45
    {
46 8
        return (int) (floor($this->offset / $this->limit) + 1);
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 8
    public function getCurrentLimit()
53
    {
54 8
        return $this->limit;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 16
    public function count()
61
    {
62 16
        return count($this->getResults());
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 4
    public function totalCount()
69
    {
70 4
        if ($this->totalCount !== null) {
71
            return $this->totalCount;
72
        }
73
74 4
        return $this->totalCount = call_user_func($this->totalCountCallback);
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 8
    public function getIterator()
81
    {
82 8
        return $this->getResults();
83
    }
84
85
    /**
86
     * @return \ArrayIterator
87
     */
88 16
    private function getResults()
89
    {
90 16
        if ($this->results !== null) {
91 8
            return $this->results;
92
        }
93
94 16
        return $this->results = new \ArrayIterator(call_user_func($this->resultCallback, $this->offset, $this->limit));
95
    }
96
}
97