-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPaginator.php
129 lines (105 loc) · 2.83 KB
/
Paginator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
/**
* This source file is proprietary and part of Rebilly.
*
* (c) Rebilly SRL
* Rebilly Ltd.
* Rebilly Inc.
*
* @see https://www.rebilly.com
*/
declare(strict_types=1);
namespace Rebilly\Sdk;
use Closure;
use Countable;
use Iterator;
use LogicException;
use OutOfBoundsException;
/**
* @template T
* @implements Iterator<array-key, Collection<T>>
*/
final class Paginator implements Iterator, Countable
{
public const DEFAULT_SIZE = 100;
private int $limit;
private int $offset;
private ?int $total;
/**
* @param null|Collection<T> $currentSegment
* @param Closure(?int,?int): Collection<T> $query
*/
public function __construct(
private ?Collection $currentSegment,
private Closure $query,
) {
$this->limit = $this->currentSegment?->getLimit() ?? self::DEFAULT_SIZE;
$this->offset = $this->currentSegment?->getOffset() ?? 0;
$this->total = $this->currentSegment?->getTotalItems();
}
/**
* @return Collection<T>
*/
public function current(): mixed
{
if ($this->currentSegment === null) {
if (!$this->valid()) {
throw new OutOfBoundsException('Cannot load segment, invalid offset');
}
$this->load();
}
if ($this->currentSegment === null) {
throw new LogicException();
}
return $this->currentSegment;
}
public function next(): void
{
$this->currentSegment = null;
$this->offset += $this->limit;
}
public function previous(): void
{
$this->currentSegment = null;
$this->offset -= $this->limit;
}
public function key(): int
{
return (int) ceil($this->offset / $this->limit);
}
public function valid(): bool
{
return $this->offset >= 0 && ($this->total === null || $this->offset <= $this->total);
}
public function rewind(): void
{
$this->currentSegment = null;
$this->offset = 0;
}
public function count(): int
{
if ($this->total === null) {
throw new LogicException('Lazy paginator has no segments loaded yet');
}
return (int) ceil($this->total / $this->limit);
}
public function isFirst(): bool
{
return $this->offset === 0;
}
public function isLast(): bool
{
return $this->total !== null && $this->offset + $this->limit >= $this->total;
}
public function getTotal(): ?int
{
return $this->total;
}
private function load(): void
{
$this->currentSegment = ($this->query)($this->limit, $this->offset);
$this->total = $this->currentSegment->getTotalItems();
$this->offset = $this->currentSegment->getOffset();
$this->limit = $this->currentSegment->getLimit();
}
}