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 Doctrine\DBAL\Query\QueryBuilder as DBALQueryBuilder; |
17
|
|
|
use Doctrine\ORM\QueryBuilder as ORMQueryBuilder; |
18
|
|
|
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator; |
19
|
|
|
use Doctrine\ORM\Tools\Pagination\Paginator; |
20
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
21
|
|
|
use Phauthentic\Pagination\PaginationParamsInterface; |
22
|
|
|
use InvalidArgumentException; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* PaginationToDoctrineRepositoryMapper |
26
|
|
|
* |
27
|
|
|
* @link https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/pagination.html |
28
|
|
|
*/ |
29
|
|
|
class Doctrine2Paginator implements PaginatorInterface |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* |
33
|
|
|
*/ |
34
|
|
|
public static $paginatorClass = Paginator::class; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Maps the params to the repository |
38
|
|
|
* |
39
|
|
|
* @param mixed $repository |
40
|
|
|
* @param \Phauthentic\Pagination\PaginationParamsInterface $paginationParams Pagination params |
41
|
|
|
* @return \Doctrine\ORM\Tools\Pagination\Paginator |
42
|
|
|
*/ |
43
|
1 |
|
public function paginate($repository, PaginationParamsInterface $paginationParams) |
44
|
|
|
{ |
45
|
|
|
/** @var $repository \Doctrine\ORM\QueryBuilder */ |
46
|
1 |
|
if (!$repository instanceof ORMQueryBuilder |
|
|
|
|
47
|
1 |
|
&& !$repository instanceof DBALQueryBuilder |
48
|
|
|
) { |
49
|
|
|
throw new InvalidArgumentException(); |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
$sortBy = $paginationParams->getSortBy(); |
53
|
1 |
|
if (!empty($sortBy)) { |
54
|
1 |
|
$repository->addOrderBy( |
55
|
1 |
|
$paginationParams->getSortBy(), |
56
|
1 |
|
$paginationParams->getDirection() |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$repository |
61
|
1 |
|
->setFirstResult($paginationParams->getOffset()) |
62
|
1 |
|
->setMaxResults($paginationParams->getLimit()); |
63
|
|
|
|
64
|
1 |
|
$paginator = new self::$paginatorClass($repository, true); |
65
|
1 |
|
$paginationParams->setCount($paginator->count()); |
66
|
|
|
|
67
|
1 |
|
return $paginator; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|