-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathPaginator.php
679 lines (605 loc) · 22.1 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.5.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Datasource;
use Cake\Core\Exception\CakeException;
use Cake\Core\InstanceConfigTrait;
use Cake\Datasource\Exception\PageOutOfBoundsException;
/**
* This class is used to handle automatic model data pagination.
*/
class Paginator implements PaginatorInterface
{
use InstanceConfigTrait;
/**
* Default pagination settings.
*
* When calling paginate() these settings will be merged with the configuration
* you provide.
*
* - `maxLimit` - The maximum limit users can choose to view. Defaults to 100
* - `limit` - The initial number of items per page. Defaults to 20.
* - `page` - The starting page, defaults to 1.
* - `allowedParameters` - A list of parameters users are allowed to set using request
* parameters. Modifying this list will allow users to have more influence
* over pagination, be careful with what you permit.
*
* @var array
*/
protected $_defaultConfig = [
'page' => 1,
'limit' => 20,
'maxLimit' => 100,
'allowedParameters' => ['limit', 'sort', 'page', 'direction'],
];
/**
* Paging params after pagination operation is done.
*
* @var array
*/
protected $_pagingParams = [];
/**
* Handles automatic pagination of model records.
*
* ### Configuring pagination
*
* When calling `paginate()` you can use the $settings parameter to pass in
* pagination settings. These settings are used to build the queries made
* and control other pagination settings.
*
* If your settings contain a key with the current table's alias. The data
* inside that key will be used. Otherwise the top level configuration will
* be used.
*
* ```
* $settings = [
* 'limit' => 20,
* 'maxLimit' => 100
* ];
* $results = $paginator->paginate($table, $settings);
* ```
*
* The above settings will be used to paginate any repository. You can configure
* repository specific settings by keying the settings with the repository alias.
*
* ```
* $settings = [
* 'Articles' => [
* 'limit' => 20,
* 'maxLimit' => 100
* ],
* 'Comments' => [ ... ]
* ];
* $results = $paginator->paginate($table, $settings);
* ```
*
* This would allow you to have different pagination settings for
* `Articles` and `Comments` repositories.
*
* ### Controlling sort fields
*
* By default CakePHP will automatically allow sorting on any column on the
* repository object being paginated. Often times you will want to allow
* sorting on either associated columns or calculated fields. In these cases
* you will need to define an allowed list of all the columns you wish to allow
* sorting on. You can define the allowed sort fields in the `$settings` parameter:
*
* ```
* $settings = [
* 'Articles' => [
* 'finder' => 'custom',
* 'sortableFields' => ['title', 'author_id', 'comment_count'],
* ]
* ];
* ```
*
* Passing an empty array as sortableFields disallows sorting altogether.
*
* ### Paginating with custom finders
*
* You can paginate with any find type defined on your table using the
* `finder` option.
*
* ```
* $settings = [
* 'Articles' => [
* 'finder' => 'popular'
* ]
* ];
* $results = $paginator->paginate($table, $settings);
* ```
*
* Would paginate using the `find('popular')` method.
*
* You can also pass an already created instance of a query to this method:
*
* ```
* $query = $this->Articles->find('popular')->matching('Tags', function ($q) {
* return $q->where(['name' => 'CakePHP'])
* });
* $results = $paginator->paginate($query);
* ```
*
* ### Scoping Request parameters
*
* By using request parameter scopes you can paginate multiple queries in
* the same controller action:
*
* ```
* $articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']);
* $tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']);
* ```
*
* Each of the above queries will use different query string parameter sets
* for pagination data. An example URL paginating both results would be:
*
* ```
* /dashboard?articles[page]=1&tags[page]=2
* ```
*
* @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The repository or query
* to paginate.
* @param array $params Request params
* @param array $settings The settings/configuration used for pagination.
* @return \Cake\Datasource\ResultSetInterface Query results
* @throws \Cake\Datasource\Exception\PageOutOfBoundsException
*/
public function paginate(object $object, array $params = [], array $settings = []): ResultSetInterface
{
$query = null;
if ($object instanceof QueryInterface) {
$query = $object;
$object = $query->getRepository();
if ($object === null) {
throw new CakeException('No repository set for query.');
}
}
$data = $this->extractData($object, $params, $settings);
$query = $this->getQuery($object, $query, $data);
$cleanQuery = clone $query;
$results = $query->all();
$data['numResults'] = count($results);
$data['count'] = $this->getCount($cleanQuery, $data);
$pagingParams = $this->buildParams($data);
$alias = $object->getAlias();
$this->_pagingParams = [$alias => $pagingParams];
if ($pagingParams['requestedPage'] > $pagingParams['page']) {
throw new PageOutOfBoundsException([
'requestedPage' => $pagingParams['requestedPage'],
'pagingParams' => $this->_pagingParams,
]);
}
return $results;
}
/**
* Get query for fetching paginated results.
*
* @param \Cake\Datasource\RepositoryInterface $object Repository instance.
* @param \Cake\Datasource\QueryInterface|null $query Query Instance.
* @param array $data Pagination data.
* @return \Cake\Datasource\QueryInterface
*/
protected function getQuery(RepositoryInterface $object, ?QueryInterface $query = null, array $data): QueryInterface
{
if ($query === null) {
$query = $object->find($data['finder'], $data['options']);
} else {
$query->applyOptions($data['options']);
}
return $query;
}
/**
* Get total count of records.
*
* @param \Cake\Datasource\QueryInterface $query Query instance.
* @param array $data Pagination data.
* @return int|null
*/
protected function getCount(QueryInterface $query, array $data): ?int
{
return $query->count();
}
/**
* Extract pagination data needed
*
* @param \Cake\Datasource\RepositoryInterface $object The repository object.
* @param array $params Request params
* @param array $settings The settings/configuration used for pagination.
* @return array Array with keys 'defaults', 'options' and 'finder'
*/
protected function extractData(RepositoryInterface $object, array $params, array $settings): array
{
$alias = $object->getAlias();
$defaults = $this->getDefaults($alias, $settings);
$options = $this->mergeOptions($params, $defaults);
$options = $this->validateSort($object, $options);
$options = $this->checkLimit($options);
$options += ['page' => 1, 'scope' => null];
$options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page'];
[$finder, $options] = $this->_extractFinder($options);
return compact('defaults', 'options', 'finder');
}
/**
* Build pagination params.
*
* @param array $data Paginator data containing keys 'options',
* 'count', 'defaults', 'finder', 'numResults'.
* @return array Paging params.
*/
protected function buildParams(array $data): array
{
$limit = $data['options']['limit'];
$paging = [
'count' => $data['count'],
'current' => $data['numResults'],
'perPage' => $limit,
'page' => $data['options']['page'],
'requestedPage' => $data['options']['page'],
];
$paging = $this->addPageCountParams($paging, $data);
$paging = $this->addStartEndParams($paging, $data);
$paging = $this->addPrevNextParams($paging, $data);
$paging = $this->addSortingParams($paging, $data);
$paging += [
'limit' => $data['defaults']['limit'] != $limit ? $limit : null,
'scope' => $data['options']['scope'],
'finder' => $data['finder'],
];
return $paging;
}
/**
* Add "page" and "pageCount" params.
*
* @param array $params Paging params.
* @param array $data Paginator data.
* @return array Updated params.
*/
protected function addPageCountParams(array $params, array $data): array
{
$page = $params['page'];
$pageCount = 0;
if ($params['count'] !== null) {
$pageCount = max((int)ceil($params['count'] / $params['perPage']), 1);
$page = min($page, $pageCount);
} elseif ($params['current'] === 0 && $params['requestedPage'] > 1) {
$page = 1;
}
$params['page'] = $page;
$params['pageCount'] = $pageCount;
return $params;
}
/**
* Add "start" and "end" params.
*
* @param array $params Paging params.
* @param array $data Paginator data.
* @return array Updated params.
*/
protected function addStartEndParams(array $params, array $data): array
{
$start = $end = 0;
if ($params['current'] > 0) {
$start = (($params['page'] - 1) * $params['perPage']) + 1;
$end = $start + $params['current'] - 1;
}
$params['start'] = $start;
$params['end'] = $end;
return $params;
}
/**
* Add "prevPage" and "nextPage" params.
*
* @param array $params Paginator params.
* @param array $data Paging data.
* @return array Updated params.
*/
protected function addPrevNextParams(array $params, array $data): array
{
$params['prevPage'] = $params['page'] > 1;
if ($params['count'] === null) {
$params['nextPage'] = true;
} else {
$params['nextPage'] = $params['count'] > $params['page'] * $params['perPage'];
}
return $params;
}
/**
* Add sorting / ordering params.
*
* @param array $params Paginator params.
* @param array $data Paging data.
* @return array Updated params.
*/
protected function addSortingParams(array $params, array $data): array
{
$defaults = $data['defaults'];
$order = (array)$data['options']['order'];
$sortDefault = $directionDefault = false;
if (!empty($defaults['order']) && count($defaults['order']) === 1) {
$sortDefault = key($defaults['order']);
$directionDefault = current($defaults['order']);
}
$params += [
'sort' => $data['options']['sort'],
'direction' => isset($data['options']['sort']) && count($order) ? current($order) : null,
'sortDefault' => $sortDefault,
'directionDefault' => $directionDefault,
'completeSort' => $order,
];
return $params;
}
/**
* Extracts the finder name and options out of the provided pagination options.
*
* @param array $options the pagination options.
* @return array An array containing in the first position the finder name
* and in the second the options to be passed to it.
*/
protected function _extractFinder(array $options): array
{
$type = !empty($options['finder']) ? $options['finder'] : 'all';
unset($options['finder'], $options['maxLimit']);
if (is_array($type)) {
$options = (array)current($type) + $options;
$type = key($type);
}
return [$type, $options];
}
/**
* Get paging params after pagination operation.
*
* @return array
*/
public function getPagingParams(): array
{
return $this->_pagingParams;
}
/**
* Shim method for reading the deprecated whitelist or allowedParameters options
*
* @return string[]
*/
protected function getAllowedParameters(): array
{
$allowed = $this->getConfig('allowedParameters');
if (!$allowed) {
$allowed = [];
}
$whitelist = $this->getConfig('whitelist');
if ($whitelist) {
deprecationWarning('The `whitelist` option is deprecated. Use the `allowedParameters` option instead.');
return array_merge($allowed, $whitelist);
}
return $allowed;
}
/**
* Shim method for reading the deprecated sortWhitelist or sortableFields options.
*
* @param array $config The configuration data to coalesce and emit warnings on.
* @return string[]|null
*/
protected function getSortableFields(array $config): ?array
{
$allowed = $config['sortableFields'] ?? null;
if ($allowed !== null) {
return $allowed;
}
$deprecated = $config['sortWhitelist'] ?? null;
if ($deprecated !== null) {
deprecationWarning('The `sortWhitelist` option is deprecated. Use `sortableFields` instead.');
}
return $deprecated;
}
/**
* Merges the various options that Paginator uses.
* Pulls settings together from the following places:
*
* - General pagination settings
* - Model specific settings.
* - Request parameters
*
* The result of this method is the aggregate of all the option sets
* combined together. You can change config value `allowedParameters` to modify
* which options/values can be set using request parameters.
*
* @param array $params Request params.
* @param array $settings The settings to merge with the request data.
* @return array Array of merged options.
*/
public function mergeOptions(array $params, array $settings): array
{
if (!empty($settings['scope'])) {
$scope = $settings['scope'];
$params = !empty($params[$scope]) ? (array)$params[$scope] : [];
}
$allowed = $this->getAllowedParameters();
$params = array_intersect_key($params, array_flip($allowed));
return array_merge($settings, $params);
}
/**
* Get the settings for a $model. If there are no settings for a specific
* repository, the general settings will be used.
*
* @param string $alias Model name to get settings for.
* @param array $settings The settings which is used for combining.
* @return array An array of pagination settings for a model,
* or the general settings.
*/
public function getDefaults(string $alias, array $settings): array
{
if (isset($settings[$alias])) {
$settings = $settings[$alias];
}
$defaults = $this->getConfig();
$defaults['whitelist'] = $defaults['allowedParameters'] = $this->getAllowedParameters();
$maxLimit = $settings['maxLimit'] ?? $defaults['maxLimit'];
$limit = $settings['limit'] ?? $defaults['limit'];
if ($limit > $maxLimit) {
$limit = $maxLimit;
}
$settings['maxLimit'] = $maxLimit;
$settings['limit'] = $limit;
return $settings + $defaults;
}
/**
* Validate that the desired sorting can be performed on the $object.
*
* Only fields or virtualFields can be sorted on. The direction param will
* also be sanitized. Lastly sort + direction keys will be converted into
* the model friendly order key.
*
* You can use the allowedParameters option to control which columns/fields are
* available for sorting via URL parameters. This helps prevent users from ordering large
* result sets on un-indexed values.
*
* If you need to sort on associated columns or synthetic properties you
* will need to use the `sortableFields` option.
*
* Any columns listed in the allowed sort fields will be implicitly trusted.
* You can use this to sort on synthetic columns, or columns added in custom
* find operations that may not exist in the schema.
*
* The default order options provided to paginate() will be merged with the user's
* requested sorting field/direction.
*
* @param \Cake\Datasource\RepositoryInterface $object Repository object.
* @param array $options The pagination options being used for this request.
* @return array An array of options with sort + direction removed and
* replaced with order if possible.
*/
public function validateSort(RepositoryInterface $object, array $options): array
{
if (isset($options['sort'])) {
$direction = null;
if (isset($options['direction'])) {
$direction = strtolower($options['direction']);
}
if (!in_array($direction, ['asc', 'desc'], true)) {
$direction = 'asc';
}
$order = isset($options['order']) && is_array($options['order']) ? $options['order'] : [];
if ($order && $options['sort'] && strpos($options['sort'], '.') === false) {
$order = $this->_removeAliases($order, $object->getAlias());
}
$options['order'] = [$options['sort'] => $direction] + $order;
} else {
$options['sort'] = null;
}
unset($options['direction']);
if (empty($options['order'])) {
$options['order'] = [];
}
if (!is_array($options['order'])) {
return $options;
}
$sortAllowed = false;
$allowed = $this->getSortableFields($options);
if ($allowed !== null) {
$options['sortableFields'] = $options['sortWhitelist'] = $allowed;
$field = key($options['order']);
$sortAllowed = in_array($field, $allowed, true);
if (!$sortAllowed) {
$options['order'] = [];
$options['sort'] = null;
return $options;
}
}
if (
$options['sort'] === null
&& count($options['order']) === 1
&& !is_numeric(key($options['order']))
) {
$options['sort'] = key($options['order']);
}
$options['order'] = $this->_prefix($object, $options['order'], $sortAllowed);
return $options;
}
/**
* Remove alias if needed.
*
* @param array $fields Current fields
* @param string $model Current model alias
* @return array $fields Unaliased fields where applicable
*/
protected function _removeAliases(array $fields, string $model): array
{
$result = [];
foreach ($fields as $field => $sort) {
if (strpos($field, '.') === false) {
$result[$field] = $sort;
continue;
}
[$alias, $currentField] = explode('.', $field);
if ($alias === $model) {
$result[$currentField] = $sort;
continue;
}
$result[$field] = $sort;
}
return $result;
}
/**
* Prefixes the field with the table alias if possible.
*
* @param \Cake\Datasource\RepositoryInterface $object Repository object.
* @param array $order Order array.
* @param bool $allowed Whether or not the field was allowed.
* @return array Final order array.
*/
protected function _prefix(RepositoryInterface $object, array $order, bool $allowed = false): array
{
$tableAlias = $object->getAlias();
$tableOrder = [];
foreach ($order as $key => $value) {
if (is_numeric($key)) {
$tableOrder[] = $value;
continue;
}
$field = $key;
$alias = $tableAlias;
if (strpos($key, '.') !== false) {
[$alias, $field] = explode('.', $key);
}
$correctAlias = ($tableAlias === $alias);
if ($correctAlias && $allowed) {
// Disambiguate fields in schema. As id is quite common.
if ($object->hasField($field)) {
$field = $alias . '.' . $field;
}
$tableOrder[$field] = $value;
} elseif ($correctAlias && $object->hasField($field)) {
$tableOrder[$tableAlias . '.' . $field] = $value;
} elseif (!$correctAlias && $allowed) {
$tableOrder[$alias . '.' . $field] = $value;
}
}
return $tableOrder;
}
/**
* Check the limit parameter and ensure it's within the maxLimit bounds.
*
* @param array $options An array of options with a limit key to be checked.
* @return array An array of options for pagination.
*/
public function checkLimit(array $options): array
{
$options['limit'] = (int)$options['limit'];
if (empty($options['limit']) || $options['limit'] < 1) {
$options['limit'] = 1;
}
$options['limit'] = max(min($options['limit'], $options['maxLimit']), 1);
return $options;
}
}