Passed
Pull Request — master (#3)
by Florian
01:38
created

Doctrine2Paginator::paginate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.072

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 3
nop 2
dl 0
loc 26
ccs 12
cts 15
cp 0.8
crap 3.072
rs 9.7666
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * Copyright (c) Phauthentic (https://github.com/Phauthentic)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Phauthentic (https://github.com/Phauthentic)
11
 * @link          https://github.com/Phauthentic
12
 * @license       https://opensource.org/licenses/mit-license.php MIT License
13
 */
14
namespace Phauthentic\Pagination\Paginator;
15
16
use Doctrine\ORM\QueryBuilder;
17
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
18
use Doctrine\ORM\Tools\Pagination\Paginator;
19
use Psr\Http\Message\ServerRequestInterface;
20
use Phauthentic\Pagination\PaginationParamsInterface;
21
use InvalidArgumentException;
22
23
/**
24
 * PaginationToDoctrineRepositoryMapper
25
 *
26
 * @link https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/pagination.html
27
 */
28
class Doctrine2Paginator implements PaginatorInterface
29
{
30
    /**
31
     * The Doctrine Paginator Class
32
     *
33
     * @var string
34
     */
35
    public static $paginatorClass = Paginator::class;
36
37
    /**
38
     * Maps the params to the repository
39
     *
40
     * @param mixed $repository
41
     * @param \Phauthentic\Pagination\PaginationParamsInterface $paginationParams Pagination params
42
     * @return \Doctrine\ORM\Tools\Pagination\Paginator
43
     */
44 1
    public function paginate($repository, PaginationParamsInterface $paginationParams)
45
    {
46 1
        if (!$repository instanceof QueryBuilder) {
47
            throw new InvalidArgumentException(sprintf(
48
                'The $repository argument must be an instance of %s for this adapter',
49
                QueryBuilder::class
50
            ));
51
        }
52
53
        /** @var $repository \Doctrine\ORM\QueryBuilder */
54 1
        $sortBy = $paginationParams->getSortBy();
55 1
        if (!empty($sortBy)) {
56 1
            $repository->addOrderBy(
57 1
                $paginationParams->getSortBy(),
58 1
                $paginationParams->getDirection()
59
            );
60
        }
61
62
        $repository
63 1
            ->setFirstResult($paginationParams->getOffset())
64 1
            ->setMaxResults($paginationParams->getLimit());
65
66 1
        $paginator = new self::$paginatorClass($repository, true);
67 1
        $paginationParams->setCount($paginator->count());
68
69 1
        return $paginator;
70
    }
71
}
72