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
![]() |
|||
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 |