|
6 | 6 |
|
7 | 7 | use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface; |
8 | 8 | use Doctrine\ORM\Tools\Pagination\Paginator; |
| 9 | +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
9 | 10 |
|
10 | 11 | abstract class PaginatedCollectionFactory |
11 | 12 | { |
| 13 | + public function __construct( |
| 14 | + private UrlGeneratorInterface $urlGenerator |
| 15 | + ) { |
| 16 | + } |
| 17 | + |
12 | 18 | abstract public function getRepository(): ServiceEntityRepositoryInterface; |
13 | 19 |
|
| 20 | + abstract public function getRouteName(): string; |
| 21 | + |
14 | 22 | public function create(int $page, int $size): PaginatedCollection |
15 | 23 | { |
16 | | - $query = $this->getRepository() |
17 | | - ->createQueryBuilder('u') |
| 24 | + $repository = $this->getRepository(); |
| 25 | + |
| 26 | + $query = $repository->createQueryBuilder('u') |
18 | 27 | ->orderBy('u.id', 'asc') |
19 | 28 | ->getQuery() |
20 | 29 | ; |
21 | 30 |
|
22 | 31 | $paginator = new Paginator($query); |
23 | 32 | $total = count($paginator); |
| 33 | + $pageCount = ceil($total / $size); |
24 | 34 |
|
25 | 35 | $paginator |
26 | 36 | ->getQuery() |
27 | 37 | ->setFirstResult($size * ($page - 1)) |
28 | | - ->setMaxResults($size); |
| 38 | + ->setMaxResults($size) |
| 39 | + ; |
| 40 | + |
| 41 | + $paginatedCollection = new PaginatedCollection($paginator->getIterator(), $total); |
| 42 | + |
| 43 | + $routeName = $this->getRouteName(); |
| 44 | + |
| 45 | + $paginatedCollection |
| 46 | + ->addLink('self', $this->urlGenerator->generate($routeName, ['page' => $page, 'size' => $size])); |
| 47 | + |
| 48 | + if (1 < $pageCount) { |
| 49 | + $paginatedCollection |
| 50 | + ->addLink('first', $this->urlGenerator->generate($routeName, ['page' => 1, 'size' => $size])) |
| 51 | + ->addLink('last', $this->urlGenerator->generate($routeName, ['page' => $pageCount, 'size' => $size])) |
| 52 | + ; |
| 53 | + } |
| 54 | + |
| 55 | + if ($page < $pageCount) { |
| 56 | + $paginatedCollection |
| 57 | + ->addLink('next', $this->urlGenerator->generate($routeName, ['page' => $page + 1, 'size' => $size])); |
| 58 | + } |
| 59 | + |
| 60 | + if ($page > 1) { |
| 61 | + $paginatedCollection |
| 62 | + ->addLink('prev', $this->urlGenerator->generate($routeName, ['page' => $page - 1, 'size' => $size])); |
| 63 | + } |
29 | 64 |
|
30 | | - return new PaginatedCollection($paginator->getIterator(), $total); |
| 65 | + return $paginatedCollection; |
31 | 66 | } |
32 | 67 | } |
0 commit comments