1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright (c) Phauthentic (https://github.com/Phauthentic) |
4
|
|
|
* |
5
|
|
|
* Licensed under The MIT License |
6
|
|
|
* For full copyright and license information, please see the LICENSE.txt |
7
|
|
|
* Redistributions of files must retain the above copyright notice. |
8
|
|
|
* |
9
|
|
|
* @copyright Copyright (c) Phauthentic (https://github.com/Phauthentic) |
10
|
|
|
* @link https://github.com/Phauthentic |
11
|
|
|
* @license https://opensource.org/licenses/mit-license.php MIT License |
12
|
|
|
*/ |
13
|
|
|
declare(strict_types = 1); |
14
|
|
|
|
15
|
|
|
namespace Phauthentic\Pagination\Paginator; |
16
|
|
|
|
17
|
|
|
use Cake\Datasource\QueryInterface; |
18
|
|
|
use Phauthentic\Pagination\PaginationParamsInterface; |
19
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Pagination To Cake Orm Mapper |
23
|
|
|
*/ |
24
|
|
|
class CakeOrmPaginator implements PaginatorInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* Maps the params to the repository |
28
|
|
|
* |
29
|
|
|
* @param \Phauthentic\Pagination\PaginationParamsInterface $paginationParams Pagination params |
30
|
|
|
* @param mixed $repository |
31
|
|
|
* @return mixed |
32
|
|
|
*/ |
33
|
|
|
public function paginate($object, PaginationParamsInterface $paginationParams) |
34
|
|
|
{ |
35
|
|
|
/** @var \Cake\Database\Query $query */ |
36
|
|
|
$query = null; |
37
|
|
|
if ($object instanceof QueryInterface) { |
38
|
|
|
$query = $object; |
39
|
|
|
$object = $query->getRepository(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$count = $query->count(); |
|
|
|
|
43
|
|
|
$paginationParams->setCount($count); |
44
|
|
|
|
45
|
|
|
$sortBy = $paginationParams->getSortBy(); |
46
|
|
|
if ($sortBy !== null) { |
47
|
|
|
if (strpos($sortBy, '.') === false) { |
48
|
|
|
$sortBy = $object->aliasField($sortBy); |
49
|
|
|
} |
50
|
|
|
if ($paginationParams->getDirection() === 'desc') { |
51
|
|
|
$query->orderDesc($sortBy); |
|
|
|
|
52
|
|
|
} else { |
53
|
|
|
$query->orderAsc($sortBy); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $query |
58
|
|
|
->limit($paginationParams->getLimit()) |
59
|
|
|
->offSet($paginationParams->getOffSet()) |
60
|
|
|
->all(); |
|
|
|
|
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|