Passed
Pull Request — master (#9)
by Roman
03:21
created

PaginateStep   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

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