CallbackPage::totalCount()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
rs 10
c 1
b 0
f 1
ccs 3
cts 4
cp 0.75
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 int $offset;
15
    private int $limit;
16
    private ?int $totalCount = null;
17
    private ?\ArrayIterator $results = null;
18
19
    /**
20
     * @param callable $resultCallback     Returns an array
21
     * @param callable $totalCountCallback Returns an integer
22
     */
23 35
    public function __construct(callable $resultCallback, callable $totalCountCallback, int $offset, int $limit)
24
    {
25 35
        $this->resultCallback = $resultCallback;
26 35
        $this->totalCountCallback = $totalCountCallback;
27 35
        $this->offset = $offset;
28 35
        $this->limit = $limit;
29 35
    }
30
31 10
    public function currentOffset(): int
32
    {
33 10
        return $this->offset;
34
    }
35
36 10
    public function currentPage(): int
37
    {
38 10
        return \floor($this->offset / $this->limit) + 1;
0 ignored issues
show
Bug Best Practice introduced by
The expression return floor($this->offset / $this->limit) + 1 returns the type double which is incompatible with the type-hinted return integer.
Loading history...
39
    }
40
41 10
    public function currentLimit(): int
42
    {
43 10
        return $this->limit;
44
    }
45
46 25
    public function count(): int
47
    {
48 25
        return \count($this->getResults());
49
    }
50
51 5
    public function totalCount(): int
52
    {
53 5
        if (null !== $this->totalCount) {
54
            return $this->totalCount;
55
        }
56
57 5
        return $this->totalCount = \call_user_func($this->totalCountCallback);
58
    }
59
60 25
    public function getIterator(): \Traversable
61
    {
62 25
        return $this->getResults();
63
    }
64
65 35
    private function getResults(): \ArrayIterator
66
    {
67 35
        if (null !== $this->results) {
68 20
            return $this->results;
69
        }
70
71 35
        return $this->results = new \ArrayIterator(\call_user_func($this->resultCallback, $this->offset, $this->limit));
72
    }
73
}
74