1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kami\ApiCoreBundle\RequestProcessor\Step\Common; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use Doctrine\ORM\Query; |
7
|
|
|
use Doctrine\ORM\QueryBuilder; |
8
|
|
|
use Doctrine\ORM\Tools\Pagination\Paginator; |
9
|
|
|
use Kami\ApiCoreBundle\Model\Pageable; |
10
|
|
|
use Kami\ApiCoreBundle\Model\PageRequest; |
11
|
|
|
use Kami\ApiCoreBundle\RequestProcessor\Step\AbstractStep; |
12
|
|
|
use Pagerfanta\Adapter\DoctrineORMAdapter; |
13
|
|
|
use Pagerfanta\Pagerfanta; |
14
|
|
|
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; |
15
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class PaginateStep |
19
|
|
|
* @package Kami\ApiCoreBundle\RequestProcessor\Step\Common |
20
|
|
|
*/ |
21
|
|
|
class PaginateStep extends AbstractStep |
22
|
|
|
{ |
23
|
|
|
protected $maxPerPage; |
24
|
|
|
|
25
|
|
|
protected $perPage; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param int $perPage |
29
|
|
|
* @param int $maxPerPage |
30
|
|
|
*/ |
31
|
1 |
|
public function __construct($perPage, $maxPerPage) |
32
|
|
|
{ |
33
|
1 |
|
$this->perPage = $perPage; |
34
|
1 |
|
$this->maxPerPage = $maxPerPage; |
35
|
1 |
|
} |
36
|
|
|
|
37
|
|
|
public function execute() |
38
|
|
|
{ |
39
|
|
|
$perPage = $this->request->query->getInt('per_page', $this->perPage); |
40
|
|
|
|
41
|
|
|
if ($perPage > $this->maxPerPage) { |
42
|
|
|
throw new BadRequestHttpException('Max per page parameter is greater than allowed'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** @var QueryBuilder $queryBuilder */ |
46
|
|
|
$queryBuilder = $this->getFromResponse('query_builder'); |
47
|
|
|
$currentPage = $this->request->query->getInt('page', 1); |
48
|
|
|
$paginator = new Pagerfanta(new DoctrineORMAdapter($queryBuilder)); |
49
|
|
|
$paginator->setMaxPerPage($perPage); |
50
|
|
|
$paginator->setCurrentPage($currentPage); |
51
|
|
|
|
52
|
|
|
if ($currentPage < 1 || $currentPage > $paginator->getNbPages()) { |
53
|
|
|
throw new NotFoundHttpException(); |
54
|
|
|
} |
55
|
|
|
return $this->createResponse(['response_data' => |
56
|
|
|
new Pageable( |
57
|
|
|
iterator_to_array($paginator->getIterator()), |
58
|
|
|
$paginator->getNbResults(), |
59
|
|
|
new PageRequest($currentPage, $paginator->getNbPages()) |
60
|
|
|
) |
61
|
|
|
]); |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
public function requiresBefore() |
65
|
|
|
{ |
66
|
1 |
|
return [BuildSelectQueryStep::class]; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
} |