Completed
Pull Request — master (#9)
by Roman
03:37
created

PaginateStep   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 42
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A requiresBefore() 0 3 1
A __construct() 0 3 1
B execute() 0 24 3
1
<?php
2
3
namespace Kami\ApiCoreBundle\RequestProcessor\Step\Common;
4
5
6
use Doctrine\ORM\QueryBuilder;
7
use Doctrine\ORM\Tools\Pagination\Paginator;
8
use Kami\ApiCoreBundle\RequestProcessor\Step\AbstractStep;
9
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
10
11
/**
12
 * Class PaginateStep
13
 * @package Kami\ApiCoreBundle\RequestProcessor\Step\Common
14
 */
15
class PaginateStep extends AbstractStep
16
{
17
    protected $maxPerPage;
18
19
    /**
20
     * @param int $maxPerPage
21
     */
22
    public function __construct($maxPerPage)
23
    {
24
        $this->maxPerPage = $maxPerPage;
25
    }
26
27
    public function execute()
28
    {
29
        /** @var QueryBuilder $queryBuilder */
30
        $queryBuilder = $this->getFromResponse('query_builder');
31
32
        $totalQueryBuilder = clone $queryBuilder;
33
        $total = (new Paginator($totalQueryBuilder))->count();
34
35
36
        $currentPage = $this->request->query->getInt('page', 1);
37
        $totalPages = ceil($total/$this->maxPerPage);
38
39
        if ($currentPage < 1 || $currentPage > $totalPages) {
40
            throw new NotFoundHttpException();
41
        }
42
43
        $queryBuilder->setFirstResult($this->maxPerPage*($currentPage - 1));
44
        $queryBuilder->setMaxResults($this->maxPerPage);
45
46
        return $this->createResponse(['response_data' => [
47
            'rows'  => $queryBuilder->getQuery()->getArrayResult(),
48
            'total' => $total,
49
            'current_page' => $currentPage,
50
            'total_pages' => $totalPages
51
        ]]);
52
    }
53
54
    public function requiresBefore()
55
    {
56
        return [BuildSelectQueryStep::class];
57
    }
58
59
}