1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
/** |
4
|
|
|
* Copyright (c) Phauthentic (https://github.com/Phauthentic) |
5
|
|
|
* |
6
|
|
|
* Licensed under The MIT License |
7
|
|
|
* For full copyright and license information, please see the LICENSE.txt |
8
|
|
|
* Redistributions of files must retain the above copyright notice. |
9
|
|
|
* |
10
|
|
|
* @copyright Copyright (c) Phauthentic (https://github.com/Phauthentic) |
11
|
|
|
* @link https://github.com/Phauthentic |
12
|
|
|
* @license https://opensource.org/licenses/mit-license.php MIT License |
13
|
|
|
*/ |
14
|
|
|
namespace Phauthentic\Pagination\Paginator; |
15
|
|
|
|
16
|
|
|
use Envms\FluentPDO\Query; |
17
|
|
|
use Envms\FluentPDO\Queries\Common; |
18
|
|
|
use Phauthentic\Pagination\PaginationParamsInterface; |
19
|
|
|
use InvalidArgumentException; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* FluentPdoPaginator |
23
|
|
|
* |
24
|
|
|
* @link https://github.com/envms/fluentpdo |
25
|
|
|
*/ |
26
|
|
|
class FluentPdoPaginator implements PaginatorInterface |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* The Doctrine Paginator Class |
30
|
|
|
* |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
public static $paginatorClass = Paginator::class; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Maps the params to the repository |
37
|
|
|
* |
38
|
|
|
* @throws \InvalidArgumentException |
39
|
|
|
* @throws \Envms\FluentPDO\Exception |
40
|
|
|
* @param \Envms\FluentPDO\Query $repository |
41
|
|
|
* @param \Phauthentic\Pagination\PaginationParamsInterface $paginationParams Pagination params |
42
|
|
|
* @return \Envms\FluentPDO\Queries\Select |
43
|
|
|
*/ |
44
|
2 |
|
public function paginate($repository, PaginationParamsInterface $paginationParams) |
45
|
|
|
{ |
46
|
2 |
|
if (!$repository instanceof Common) { |
|
|
|
|
47
|
|
|
throw new InvalidArgumentException(sprintf( |
48
|
|
|
'$repository must be an instance of %s', |
49
|
|
|
Common::class |
50
|
|
|
)); |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
$countQuery = clone $repository; |
54
|
2 |
|
$countQuery->select('COUNT(*) AS __count__'); |
55
|
2 |
|
$paginationParams->setCount((int)$countQuery->fetch()['__count__']); |
56
|
|
|
|
57
|
|
|
/** @var $repository \Envms\FluentPDO\Query */ |
58
|
2 |
|
$sortBy = $paginationParams->getSortBy(); |
59
|
2 |
|
if ($sortBy !== null) { |
60
|
1 |
|
$repository->orderBy($sortBy . ' ' . $paginationParams->getDirection()); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $repository |
64
|
2 |
|
->limit($paginationParams->getLimit()) |
65
|
2 |
|
->offset($paginationParams->getOffset()); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|