Passed
Pull Request — master (#27)
by Iakov
04:00
created

PaginateStep   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 27.27%

Importance

Changes 0
Metric Value
dl 0
loc 46
ccs 6
cts 22
cp 0.2727
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 4 1
B execute() 0 23 4
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
}