Passed
Pull Request — master (#153)
by Alexander
05:55 queued 02:54
created

KeysetPaginator::isOnLastPage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Data\Paginator;
6
7
use Closure;
8
use InvalidArgumentException;
9
use RuntimeException;
10
use Yiisoft\Arrays\ArrayHelper;
11
use Yiisoft\Data\Reader\Filter\GreaterThan;
12
use Yiisoft\Data\Reader\Filter\GreaterThanOrEqual;
13
use Yiisoft\Data\Reader\Filter\LessThan;
14
use Yiisoft\Data\Reader\Filter\LessThanOrEqual;
15
use Yiisoft\Data\Reader\FilterableDataInterface;
16
use Yiisoft\Data\Reader\FilterInterface;
17
use Yiisoft\Data\Reader\LimitableDataInterface;
18
use Yiisoft\Data\Reader\ReadableDataInterface;
19
use Yiisoft\Data\Reader\Sort;
20
use Yiisoft\Data\Reader\SortableDataInterface;
21
22
use function array_reverse;
23
use function count;
24
use function key;
25
use function reset;
26
use function sprintf;
27
28
/**
29
 * Keyset paginator.
30
 *
31
 * Advantages:
32
 *
33
 * - Performance does not depend on page number
34
 * - Consistent results regardless of insertions and deletions
35
 *
36
 * Disadvantages:
37
 *
38
 * - Total number of pages is not available
39
 * - Can not get to specific page, only "previous" and "next"
40
 * - Data cannot be unordered
41
 *
42
 * @link https://use-the-index-luke.com/no-offset
43
 *
44
 * @template TKey as array-key
45
 * @template TValue as array|object
46
 *
47
 * @implements PaginatorInterface<TKey, TValue>
48
 *
49
 * @psalm-type FilterCallback = Closure(GreaterThan|LessThan|GreaterThanOrEqual|LessThanOrEqual,KeysetFilterContext):FilterInterface
50
 */
51
final class KeysetPaginator implements PaginatorInterface
52
{
53
    /**
54
     * Data reader being paginated.
55
     *
56
     * @psalm-var ReadableDataInterface<TKey, TValue>&LimitableDataInterface&FilterableDataInterface&SortableDataInterface
57
     */
58
    private ReadableDataInterface $dataReader;
59
60
    /**
61
     * @var int Maximum number of items per page.
62
     */
63
    private int $pageSize = self::DEFAULT_PAGE_SIZE;
64
    private ?string $firstValue = null;
65
    private ?string $lastValue = null;
66
    private ?string $currentFirstValue = null;
67
    private ?string $currentLastValue = null;
68
69
    /**
70
     * @var bool Whether there is previous page.
71
     */
72
    private bool $hasPreviousPage = false;
73
74
    /**
75
     * @var bool Whether there is next page.
76
     */
77
    private bool $hasNextPage = false;
78
79
    /**
80
     * @psalm-var FilterCallback|null
81
     */
82
    private ?Closure $filterCallback = null;
83
84
    /**
85
     * Reader cache against repeated scans.
86
     * See more {@see __clone()} and {@see initialize()}.
87
     *
88
     * @psalm-var null|array<TKey, TValue>
89
     */
90
    private ?array $readCache = null;
91
92
    /**
93
     * @param ReadableDataInterface $dataReader Data reader being paginated.
94
     * @psalm-param ReadableDataInterface<TKey, TValue>&LimitableDataInterface&FilterableDataInterface&SortableDataInterface $dataReader
95
     * @psalm-suppress DocblockTypeContradiction Needed to allow validating `$dataReader`
96
     */
97 46
    public function __construct(ReadableDataInterface $dataReader)
98
    {
99 46
        if (!$dataReader instanceof FilterableDataInterface) {
100 1
            throw new InvalidArgumentException(sprintf(
101 1
                'Data reader should implement "%s" to be used with keyset paginator.',
102 1
                FilterableDataInterface::class,
103 1
            ));
104
        }
105
106 45
        if (!$dataReader instanceof SortableDataInterface) {
107 1
            throw new InvalidArgumentException(sprintf(
108 1
                'Data reader should implement "%s" to be used with keyset paginator.',
109 1
                SortableDataInterface::class,
110 1
            ));
111
        }
112
113 44
        if (!$dataReader instanceof LimitableDataInterface) {
114 1
            throw new InvalidArgumentException(sprintf(
115 1
                'Data reader should implement "%s" to be used with keyset paginator.',
116 1
                LimitableDataInterface::class,
117 1
            ));
118
        }
119
120 43
        $sort = $dataReader->getSort();
121
122 43
        if ($sort === null) {
123 1
            throw new RuntimeException('Data sorting should be configured to work with keyset pagination.');
124
        }
125
126 42
        if (empty($sort->getOrder())) {
127 1
            throw new RuntimeException('Data should be always sorted to work with keyset pagination.');
128
        }
129
130 41
        $this->dataReader = $dataReader;
131
    }
132
133 38
    public function __clone()
134
    {
135 38
        $this->readCache = null;
136 38
        $this->hasPreviousPage = false;
137 38
        $this->hasNextPage = false;
138 38
        $this->currentFirstValue = null;
139 38
        $this->currentLastValue = null;
140
    }
141
142 12
    public function withNextPageToken(?string $token): static
143
    {
144 12
        $new = clone $this;
145 12
        $new->firstValue = null;
146 12
        $new->lastValue = $token;
147 12
        return $new;
148
    }
149
150 10
    public function withPreviousPageToken(?string $token): static
151
    {
152 10
        $new = clone $this;
153 10
        $new->firstValue = $token;
154 10
        $new->lastValue = null;
155 10
        return $new;
156
    }
157
158 33
    public function withPageSize(int $pageSize): static
159
    {
160 33
        if ($pageSize < 1) {
161 1
            throw new InvalidArgumentException('Page size should be at least 1.');
162
        }
163
164 32
        $new = clone $this;
165 32
        $new->pageSize = $pageSize;
166 32
        return $new;
167
    }
168
169
    /**
170
     * Returns a new instance with defined closure for preparing the page value before use in data reader filters.
171
     *
172
     * @psalm-param FilterCallback|null $callback
173
     */
174 4
    public function withFilterCallback(?Closure $callback): self
175
    {
176 4
        $new = clone $this;
177 4
        $new->filterCallback = $callback;
178 4
        return $new;
179
    }
180
181
    /**
182
     * Reads items of the page.
183
     *
184
     * This method uses the read cache to prevent duplicate reads from the data source. See more {@see resetInternal()}.
185
     */
186 37
    public function read(): iterable
187
    {
188 37
        if ($this->readCache !== null) {
189 2
            return $this->readCache;
190
        }
191
192
        /** @var Sort $sort */
193 37
        $sort = $this->dataReader->getSort();
0 ignored issues
show
Bug introduced by
The method getSort() does not exist on Yiisoft\Data\Reader\ReadableDataInterface. It seems like you code against a sub-type of said class. However, the method does not exist in anonymous//tests/Paginat...fsetPaginatorTest.php$2 or anonymous//tests/Paginat...fsetPaginatorTest.php$1 or anonymous//tests/Paginat...ysetPaginatorTest.php$2 or anonymous//tests/Paginat...fsetPaginatorTest.php$0. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

193
        /** @scrutinizer ignore-call */ 
194
        $sort = $this->dataReader->getSort();
Loading history...
194
        /** @infection-ignore-all Any value more one in line below will be ignored into `readData()` method */
195 37
        $dataReader = $this->dataReader->withLimit($this->pageSize + 1);
0 ignored issues
show
Bug introduced by
The method withLimit() does not exist on Yiisoft\Data\Reader\ReadableDataInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Yiisoft\Data\Paginator\PaginatorInterface or anonymous//tests/Paginat...ysetPaginatorTest.php$0 or anonymous//tests/Paginat...fsetPaginatorTest.php$2 or Yiisoft\Data\Paginator\OffsetPaginator or Yiisoft\Data\Paginator\KeysetPaginator. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

195
        /** @scrutinizer ignore-call */ 
196
        $dataReader = $this->dataReader->withLimit($this->pageSize + 1);
Loading history...
196
197 37
        if ($this->isGoingToPreviousPage()) {
198 9
            $sort = $this->reverseSort($sort);
199 9
            $dataReader = $dataReader->withSort($sort);
200
        }
201
202 37
        if ($this->isGoingSomewhere()) {
203 13
            $dataReader = $dataReader->withFilter($this->getFilter($sort));
204 13
            $this->hasPreviousPage = $this->previousPageExist($dataReader, $sort);
205
        }
206
207 37
        $data = $this->readData($dataReader, $sort);
208
209 37
        if ($this->isGoingToPreviousPage()) {
210 9
            $data = $this->reverseData($data);
211
        }
212
213 37
        return $this->readCache = $data;
214
    }
215
216 2
    public function readOne(): array|object|null
217
    {
218 2
        foreach ($this->read() as $item) {
219 1
            return $item;
220
        }
221
222 1
        return null;
223
    }
224
225 2
    public function getPageSize(): int
226
    {
227 2
        return $this->pageSize;
228
    }
229
230 2
    public function getCurrentPageSize(): int
231
    {
232 2
        $this->initialize();
233 2
        return count($this->readCache);
0 ignored issues
show
Bug introduced by
It seems like $this->readCache can also be of type null; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

233
        return count(/** @scrutinizer ignore-type */ $this->readCache);
Loading history...
234
    }
235
236 3
    public function getPreviousPageToken(): ?string
237
    {
238 3
        return $this->isOnFirstPage() ? null : $this->currentFirstValue;
239
    }
240
241 9
    public function getNextPageToken(): ?string
242
    {
243 9
        return $this->isOnLastPage() ? null : $this->currentLastValue;
244
    }
245
246 1
    public function getSort(): ?Sort
247
    {
248
        /** @psalm-var SortableDataInterface $this->dataReader */
249 1
        return $this->dataReader->getSort();
250
    }
251
252 27
    public function isOnFirstPage(): bool
253
    {
254 27
        if ($this->lastValue === null && $this->firstValue === null) {
255 20
            return true;
256
        }
257
258 7
        $this->initialize();
259 7
        return !$this->hasPreviousPage;
260
    }
261
262 28
    public function isOnLastPage(): bool
263
    {
264 28
        $this->initialize();
265 28
        return !$this->hasNextPage;
266
    }
267
268 3
    public function isPaginationRequired(): bool
269
    {
270 3
        return !$this->isOnFirstPage() || !$this->isOnLastPage();
271
    }
272
273
    /**
274
     * @psalm-assert array<TKey, TValue> $this->readCache
275
     */
276 30
    private function initialize(): void
277
    {
278 30
        if ($this->readCache !== null) {
279 13
            return;
280
        }
281
282 22
        $cache = [];
283
284 22
        foreach ($this->read() as $key => $value) {
285 16
            $cache[$key] = $value;
286
        }
287
288 22
        $this->readCache = $cache;
289
    }
290
291
    /**
292
     * @psalm-param ReadableDataInterface<TKey, TValue> $dataReader
293
     * @psalm-return array<TKey, TValue>
294
     */
295 37
    private function readData(ReadableDataInterface $dataReader, Sort $sort): array
296
    {
297 37
        $data = [];
298 37
        [$field] = $this->getFieldAndSortingFromSort($sort);
299
300 37
        foreach ($dataReader->read() as $key => $item) {
301 30
            if ($this->currentFirstValue === null) {
302 30
                $this->currentFirstValue = (string) ArrayHelper::getValue($item, $field);
303
            }
304
305 30
            if (count($data) === $this->pageSize) {
306 16
                $this->hasNextPage = true;
307
            } else {
308 30
                $this->currentLastValue = (string) ArrayHelper::getValue($item, $field);
309 30
                $data[$key] = $item;
310
            }
311
        }
312
313 37
        return $data;
314
    }
315
316
    /**
317
     * @psalm-param array<TKey, TValue> $data
318
     * @psalm-return array<TKey, TValue>
319
     */
320 9
    private function reverseData(array $data): array
321
    {
322 9
        [$this->currentFirstValue, $this->currentLastValue] = [$this->currentLastValue, $this->currentFirstValue];
323 9
        [$this->hasPreviousPage, $this->hasNextPage] = [$this->hasNextPage, $this->hasPreviousPage];
324 9
        return array_reverse($data, true);
325
    }
326
327
    /**
328
     * @psalm-param ReadableDataInterface<TKey, TValue>&LimitableDataInterface&FilterableDataInterface&SortableDataInterface $dataReader
329
     */
330 14
    private function previousPageExist(ReadableDataInterface $dataReader, Sort $sort): bool
331
    {
332 14
        $reverseFilter = $this->getReverseFilter($sort);
333
334 14
        return !empty($dataReader->withFilter($reverseFilter)->readOne());
0 ignored issues
show
Bug introduced by
The method withFilter() does not exist on Yiisoft\Data\Reader\ReadableDataInterface. It seems like you code against a sub-type of Yiisoft\Data\Reader\ReadableDataInterface such as anonymous//tests/Paginat...ysetPaginatorTest.php$0 or anonymous//tests/Paginat...ysetPaginatorTest.php$2 or Yiisoft\Data\Reader\DataReaderInterface or Yiisoft\Data\Tests\Support\MutationDataReader. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

334
        return !empty($dataReader->/** @scrutinizer ignore-call */ withFilter($reverseFilter)->readOne());
Loading history...
335
    }
336
337 14
    private function getFilter(Sort $sort): FilterInterface
338
    {
339 14
        $value = $this->getValue();
340 14
        [$field, $sorting] = $this->getFieldAndSortingFromSort($sort);
341
342 14
        $filter = $sorting === SORT_ASC ? new GreaterThan($field, $value) : new LessThan($field, $value);
343 14
        if ($this->filterCallback === null) {
344 11
            return $filter;
345
        }
346
347 3
        return ($this->filterCallback)(
348 3
            $filter,
349 3
            new KeysetFilterContext(
350 3
                $field,
351 3
                $value,
352 3
                $sorting,
353 3
                false,
354 3
            )
355 3
        );
356
    }
357
358 15
    private function getReverseFilter(Sort $sort): FilterInterface
359
    {
360 15
        $value = $this->getValue();
361 15
        [$field, $sorting] = $this->getFieldAndSortingFromSort($sort);
362
363 15
        $filter = $sorting === SORT_ASC ? new LessThanOrEqual($field, $value) : new GreaterThanOrEqual($field, $value);
364 15
        if ($this->filterCallback === null) {
365 12
            return $filter;
366
        }
367
368 3
        return ($this->filterCallback)(
369 3
            $filter,
370 3
            new KeysetFilterContext(
371 3
                $field,
372 3
                $value,
373 3
                $sorting,
374 3
                true,
375 3
            )
376 3
        );
377
    }
378
379
    /**
380
     * @psalm-suppress NullableReturnStatement, InvalidNullableReturnType, PossiblyNullArgument The code calling this
381
     * method must ensure that at least one of the properties `$firstValue` or `$lastValue` is not `null`.
382
     */
383 16
    private function getValue(): string
384
    {
385 16
        return $this->isGoingToPreviousPage() ? $this->firstValue : $this->lastValue;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->isGoingToP...alue : $this->lastValue could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
386
    }
387
388 9
    private function reverseSort(Sort $sort): Sort
389
    {
390 9
        $order = $sort->getOrder();
391
392 9
        foreach ($order as &$sorting) {
393 9
            $sorting = $sorting === 'asc' ? 'desc' : 'asc';
394
        }
395
396 9
        return $sort->withOrder($order);
397
    }
398
399
    /**
400
     * @psalm-return array{0: string, 1: int}
401
     */
402 40
    private function getFieldAndSortingFromSort(Sort $sort): array
403
    {
404 40
        $order = $sort->getOrder();
405
406 40
        return [
407 40
            (string) key($order),
408 40
            reset($order) === 'asc' ? SORT_ASC : SORT_DESC,
409 40
        ];
410
    }
411
412 40
    private function isGoingToPreviousPage(): bool
413
    {
414 40
        return $this->firstValue !== null && $this->lastValue === null;
415
    }
416
417 37
    private function isGoingSomewhere(): bool
418
    {
419 37
        return $this->firstValue !== null || $this->lastValue !== null;
420
    }
421
}
422