Completed
Push — master ( 03a8c3...2d8113 )
by Peter
02:49
created

Builder::paginate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * AnimeDb package.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2011, Peter Gribanov
7
 * @license   http://opensource.org/licenses/MIT
8
 */
9
namespace AnimeDb\Bundle\PaginationBundle\Service;
10
11
use Doctrine\ORM\QueryBuilder;
12
13
/**
14
 * @author  Peter Gribanov <[email protected]>
15
 */
16
class Builder
17
{
18
    /**
19
     * The number of pages displayed in the navigation.
20
     *
21
     * @var int
22
     */
23
    protected $max_navigate = Configuration::DEFAULT_LIST_LENGTH;
24
25
    /**
26
     * @param int $max_navigate
27
     */
28 4
    public function __construct($max_navigate)
29
    {
30 4
        $this->max_navigate = $max_navigate;
31 4
    }
32
33
    /**
34
     * @param int $total_pages
35
     * @param int $current_page
36
     *
37
     * @return Configuration
38
     */
39 2
    public function paginate($total_pages = 0, $current_page = 1)
40
    {
41 2
        return (new Configuration($total_pages, $current_page))
42 2
            ->setMaxNavigate($this->max_navigate);
43
    }
44
45
    /**
46
     * @param QueryBuilder $query
47
     * @param int $per_page
48
     * @param int $current_page
49
     *
50
     * @return Configuration
51
     */
52 2
    public function paginateQuery(QueryBuilder $query, $per_page, $current_page = 1)
53
    {
54 2
        $counter = clone $query;
55
        $total = $counter
56 2
            ->select(sprintf('COUNT(%s)', current($query->getRootAliases())))
57 2
            ->getQuery()
58 2
            ->getSingleScalarResult();
59
60
        $query
61 2
            ->setFirstResult(($current_page - 1) * $per_page)
62 2
            ->setMaxResults($per_page);
63
64 2
        return (new Configuration(ceil($total / $per_page), $current_page))
65 2
            ->setMaxNavigate($this->max_navigate);
66
    }
67
}
68