Passed
Push — master ( 31f22c...5a83e4 )
by Florian
59s
created

FluentPdoPaginator::paginate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.1105

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 3
nop 2
dl 0
loc 22
ccs 10
cts 13
cp 0.7692
crap 3.1105
rs 9.8333
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 Envms\FluentPDO\Query;
17
use Envms\FluentPDO\Queries\Common;
18
use Phauthentic\Pagination\PaginationParamsInterface;
19
use InvalidArgumentException;
20
21
/**
22
 * FluentPdoPaginator
23
 *
24
 * @link https://github.com/envms/fluentpdo
25
 */
26
class FluentPdoPaginator implements PaginatorInterface
27
{
28
    /**
29
     * The Doctrine Paginator Class
30
     *
31
     * @var string
32
     */
33
    public static $paginatorClass = Paginator::class;
34
35
    /**
36
     * Maps the params to the repository
37
     *
38
     * @throws \InvalidArgumentException
39
     * @throws \Envms\FluentPDO\Exception
40
     * @param \Envms\FluentPDO\Query $repository
41
     * @param \Phauthentic\Pagination\PaginationParamsInterface $paginationParams Pagination params
42
     * @return \Envms\FluentPDO\Queries\Select
43
     */
44 2
    public function paginate($repository, PaginationParamsInterface $paginationParams)
45
    {
46 2
        if (!$repository instanceof Common) {
0 ignored issues
show
introduced by
$repository is never a sub-type of Envms\FluentPDO\Queries\Common.
Loading history...
47
            throw new InvalidArgumentException(sprintf(
48
                '$repository must be an instance of %s',
49
                Common::class
50
            ));
51
        }
52
53 2
        $countQuery = clone $repository;
54 2
        $countQuery->select('COUNT(*) AS __count__');
55 2
        $paginationParams->setCount((int)$countQuery->fetch()['__count__']);
56
57
        /** @var $repository \Envms\FluentPDO\Query */
58 2
        $sortBy = $paginationParams->getSortBy();
59 2
        if ($sortBy !== null) {
60 1
            $repository->orderBy($sortBy . ' ' . $paginationParams->getDirection());
61
        }
62
63
        return $repository
64 2
            ->limit($paginationParams->getLimit())
65 2
            ->offset($paginationParams->getOffset());
66
    }
67
}
68