Test Failed
Pull Request — master (#159)
by Sergei
04:47 queued 02:18
created

KeysetPaginator::getNextToken()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 4
nop 0
dl 0
loc 5
ccs 2
cts 2
cp 1
crap 3
rs 10
c 0
b 0
f 0
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 ?PageToken $token = null;
65
    private ?string $currentFirstValue = null;
66
    private ?string $currentLastValue = null;
67
68
    /**
69
     * @var bool Whether there is previous page.
70
     */
71
    private bool $hasPreviousPage = false;
72
73
    /**
74
     * @var bool Whether there is next page.
75
     */
76
    private bool $hasNextPage = false;
77
78
    /**
79
     * @psalm-var FilterCallback|null
80
     */
81
    private ?Closure $filterCallback = null;
82
83
    /**
84
     * Reader cache against repeated scans.
85
     * See more {@see __clone()} and {@see initialize()}.
86
     *
87
     * @psalm-var null|array<TKey, TValue>
88
     */
89
    private ?array $readCache = null;
90
91
    /**
92
     * @param ReadableDataInterface $dataReader Data reader being paginated.
93
     * @psalm-param ReadableDataInterface<TKey, TValue>&LimitableDataInterface&FilterableDataInterface&SortableDataInterface $dataReader
94
     * @psalm-suppress DocblockTypeContradiction Needed to allow validating `$dataReader`
95
     */
96
    public function __construct(ReadableDataInterface $dataReader)
97 80
    {
98
        if (!$dataReader instanceof FilterableDataInterface) {
99 80
            throw new InvalidArgumentException(sprintf(
100 1
                'Data reader should implement "%s" to be used with keyset paginator.',
101 1
                FilterableDataInterface::class,
102 1
            ));
103 1
        }
104
105
        if (!$dataReader instanceof SortableDataInterface) {
106 79
            throw new InvalidArgumentException(sprintf(
107 1
                'Data reader should implement "%s" to be used with keyset paginator.',
108 1
                SortableDataInterface::class,
109 1
            ));
110 1
        }
111
112
        if (!$dataReader instanceof LimitableDataInterface) {
113 78
            throw new InvalidArgumentException(sprintf(
114 1
                'Data reader should implement "%s" to be used with keyset paginator.',
115 1
                LimitableDataInterface::class,
116 1
            ));
117 1
        }
118
119
        $sort = $dataReader->getSort();
120 77
121
        if ($sort === null) {
122 77
            throw new RuntimeException('Data sorting should be configured to work with keyset pagination.');
123 1
        }
124
125
        if (empty($sort->getOrder())) {
126 76
            throw new RuntimeException('Data should be always sorted to work with keyset pagination.');
127 1
        }
128
129
        $this->dataReader = $dataReader;
130 75
    }
131
132
    public function __clone()
133 71
    {
134
        $this->readCache = null;
135 71
        $this->hasPreviousPage = false;
136 71
        $this->hasNextPage = false;
137 71
        $this->currentFirstValue = null;
138 71
        $this->currentLastValue = null;
139 71
    }
140
141
    public function withToken(?PageToken $token): static
142 28
    {
143
        $new = clone $this;
144 28
        $new->token = $token;
145 28
        return $new;
146 28
    }
147 28
148
    public function getToken(): ?PageToken
149
    {
150 26
        return $this->token;
151
    }
152 26
153 26
    public function withPageSize(int $pageSize): static
154 26
    {
155 26
        if ($pageSize < 1) {
156
            throw new InvalidArgumentException('Page size should be at least 1.');
157
        }
158 65
159
        $new = clone $this;
160 65
        $new->pageSize = $pageSize;
161 1
        return $new;
162
    }
163
164 64
    /**
165 64
     * Returns a new instance with defined closure for preparing data reader filters.
166 64
     *
167
     * @psalm-param FilterCallback|null $callback Closure with signature:
168
     *
169
     * ```php
170
     * function(
171
     *    GreaterThan|LessThan|GreaterThanOrEqual|LessThanOrEqual $filter,
172
     *    KeysetFilterContext $context
173
     * ): FilterInterface
174
     * ```
175
     */
176
    public function withFilterCallback(?Closure $callback): self
177
    {
178
        $new = clone $this;
179
        $new->filterCallback = $callback;
180
        return $new;
181 4
    }
182
183 4
    /**
184 4
     * Reads items of the page.
185 4
     *
186
     * This method uses the read cache to prevent duplicate reads from the data source. See more {@see resetInternal()}.
187
     */
188
    public function read(): iterable
189
    {
190
        if ($this->readCache !== null) {
191
            return $this->readCache;
192
        }
193 69
194
        /** @var Sort $sort */
195 69
        $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 Yiisoft\Data\Reader\ReadableDataInterface such as Yiisoft\Data\Paginator\PaginatorInterface or anonymous//tests/Paginat...ysetPaginatorTest.php$0 or anonymous//tests/Paginat...ysetPaginatorTest.php$3 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

195
        /** @scrutinizer ignore-call */ 
196
        $sort = $this->dataReader->getSort();
Loading history...
196 34
        /** @infection-ignore-all Any value more one in line below will be ignored into `readData()` method */
197
        $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

197
        /** @scrutinizer ignore-call */ 
198
        $dataReader = $this->dataReader->withLimit($this->pageSize + 1);
Loading history...
198
199
        if ($this->token?->isPrevious === true) {
200 69
            $sort = $this->reverseSort($sort);
201
            $dataReader = $dataReader->withSort($sort);
202 69
        }
203
204 69
        if ($this->token !== null) {
205 25
            $dataReader = $dataReader->withFilter($this->getFilter($sort));
206 25
            $this->hasPreviousPage = $this->previousPageExist($dataReader, $sort);
207
        }
208
209 69
        $data = $this->readData($dataReader, $sort);
210 45
211 45
        if ($this->token?->isPrevious === true) {
212
            $data = $this->reverseData($data);
213
        }
214 69
215
        return $this->readCache = $data;
216 69
    }
217 25
218
    public function readOne(): array|object|null
219
    {
220 69
        foreach ($this->read() as $item) {
221
            return $item;
222
        }
223 2
224
        return null;
225 2
    }
226 1
227
    public function getPageSize(): int
228
    {
229 1
        return $this->pageSize;
230
    }
231
232 2
    public function getCurrentPageSize(): int
233
    {
234 2
        $this->initialize();
235
        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

235
        return count(/** @scrutinizer ignore-type */ $this->readCache);
Loading history...
236
    }
237 2
238
    public function getPreviousToken(): ?PageToken
239 2
    {
240 2
        return $this->isOnFirstPage()
241
            ? null
242
            : ($this->currentFirstValue === null ? null : PageToken::previous($this->currentFirstValue));
243 3
    }
244
245 3
    public function getNextToken(): ?PageToken
246
    {
247
        return $this->isOnLastPage()
248 9
            ? null
249
            : ($this->currentLastValue === null ? null : PageToken::next($this->currentLastValue));
250 9
    }
251
252
    public function isSortable(): bool
253 1
    {
254
        return true;
255 1
    }
256
257
    public function withSort(?Sort $sort): static
258 1
    {
259
        $new = clone $this;
260 1
        $new->dataReader = $this->dataReader->withSort($sort);
0 ignored issues
show
Bug introduced by
The method withSort() does not exist on Yiisoft\Data\Reader\ReadableDataInterface. It seems like you code against a sub-type of Yiisoft\Data\Reader\ReadableDataInterface such as Yiisoft\Data\Paginator\PaginatorInterface or anonymous//tests/Paginat...ysetPaginatorTest.php$0 or anonymous//tests/Paginat...ysetPaginatorTest.php$3 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

260
        /** @scrutinizer ignore-call */ 
261
        $new->dataReader = $this->dataReader->withSort($sort);
Loading history...
261 1
        return $new;
262 1
    }
263
264
    public function getSort(): ?Sort
265 2
    {
266
        return $this->dataReader->getSort();
267 2
    }
268
269
    public function isOnFirstPage(): bool
270 59
    {
271
        if ($this->token === null) {
272 59
            return true;
273 20
        }
274
275
        $this->initialize();
276 39
        return !$this->hasPreviousPage;
277 39
    }
278
279
    public function isOnLastPage(): bool
280 60
    {
281
        $this->initialize();
282 60
        return !$this->hasNextPage;
283 60
    }
284
285
    public function isPaginationRequired(): bool
286 3
    {
287
        return !$this->isOnFirstPage() || !$this->isOnLastPage();
288 3
    }
289
290
    /**
291
     * @psalm-assert array<TKey, TValue> $this->readCache
292
     */
293
    private function initialize(): void
294 62
    {
295
        if ($this->readCache !== null) {
296 62
            return;
297 45
        }
298
299
        $cache = [];
300 54
301
        foreach ($this->read() as $key => $value) {
302 54
            $cache[$key] = $value;
303 36
        }
304
305
        $this->readCache = $cache;
306 54
    }
307
308
    /**
309
     * @psalm-param ReadableDataInterface<TKey, TValue> $dataReader
310
     * @psalm-return array<TKey, TValue>
311
     */
312
    private function readData(ReadableDataInterface $dataReader, Sort $sort): array
313 69
    {
314
        $data = [];
315 69
        [$field] = $this->getFieldAndSortingFromSort($sort);
316 69
317
        foreach ($dataReader->read() as $key => $item) {
318 69
            if ($this->currentFirstValue === null) {
319 50
                $this->currentFirstValue = (string) ArrayHelper::getValue($item, $field);
320 50
            }
321
322
            if (count($data) === $this->pageSize) {
323 50
                $this->hasNextPage = true;
324 28
            } else {
325
                $this->currentLastValue = (string) ArrayHelper::getValue($item, $field);
326 50
                $data[$key] = $item;
327 50
            }
328
        }
329
330
        return $data;
331 69
    }
332
333
    /**
334
     * @psalm-param array<TKey, TValue> $data
335
     * @psalm-return array<TKey, TValue>
336
     */
337
    private function reverseData(array $data): array
338 25
    {
339
        [$this->currentFirstValue, $this->currentLastValue] = [$this->currentLastValue, $this->currentFirstValue];
340 25
        [$this->hasPreviousPage, $this->hasNextPage] = [$this->hasNextPage, $this->hasPreviousPage];
341 25
        return array_reverse($data, true);
342 25
    }
343
344
    /**
345
     * @psalm-param ReadableDataInterface<TKey, TValue>&LimitableDataInterface&FilterableDataInterface&SortableDataInterface $dataReader
346
     */
347
    private function previousPageExist(ReadableDataInterface $dataReader, Sort $sort): bool
348 46
    {
349
        $reverseFilter = $this->getReverseFilter($sort);
350 46
351
        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

351
        return !empty($dataReader->/** @scrutinizer ignore-call */ withFilter($reverseFilter)->readOne());
Loading history...
352 46
    }
353
354
    private function getFilter(Sort $sort): FilterInterface
355 46
    {
356
        /**
357 46
         * @psalm-var PageToken $this->token The code calling this method must ensure that page token is not null.
358 46
         */
359
        $value = $this->token->value;
360 46
        [$field, $sorting] = $this->getFieldAndSortingFromSort($sort);
361 46
362 43
        $filter = $sorting === SORT_ASC ? new GreaterThan($field, $value) : new LessThan($field, $value);
363
        if ($this->filterCallback === null) {
364
            return $filter;
365 3
        }
366 3
367 3
        return ($this->filterCallback)(
368 3
            $filter,
369 3
            new KeysetFilterContext(
370 3
                $field,
371 3
                $value,
372 3
                $sorting,
373 3
                false,
374
            )
375
        );
376 47
    }
377
378 47
    private function getReverseFilter(Sort $sort): FilterInterface
379 47
    {
380
        /**
381 47
         * @psalm-var PageToken $this->token The code calling this method must ensure that page token is not null.
382 47
         */
383 44
        $value = $this->token->value;
384
        [$field, $sorting] = $this->getFieldAndSortingFromSort($sort);
385
386 3
        $filter = $sorting === SORT_ASC ? new LessThanOrEqual($field, $value) : new GreaterThanOrEqual($field, $value);
387 3
        if ($this->filterCallback === null) {
388 3
            return $filter;
389 3
        }
390 3
391 3
        return ($this->filterCallback)(
392 3
            $filter,
393 3
            new KeysetFilterContext(
394 3
                $field,
395
                $value,
396
                $sorting,
397
                true,
398
            )
399
        );
400
    }
401 48
402
    private function reverseSort(Sort $sort): Sort
403 48
    {
404
        $order = $sort->getOrder();
405
406 25
        foreach ($order as &$sorting) {
407
            $sorting = $sorting === 'asc' ? 'desc' : 'asc';
408 25
        }
409
410 25
        return $sort->withOrder($order);
411 25
    }
412
413
    /**
414 25
     * @psalm-return array{0: string, 1: int}
415
     */
416
    private function getFieldAndSortingFromSort(Sort $sort): array
417
    {
418
        $order = $sort->getOrder();
419
420 72
        return [
421
            (string) key($order),
422 72
            reset($order) === 'asc' ? SORT_ASC : SORT_DESC,
423
        ];
424 72
    }
425
}
426