Completed
Pull Request — master (#1922)
by chihiro
109:34
created

PaginatorAdapter::paginate()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 21
nc 3
nop 4
dl 0
loc 37
ccs 21
cts 21
cp 1
crap 3
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Eccube\Doctrine\ORM\Tools;
4
5
use Doctrine\ORM\Query;
6
use Doctrine\ORM\QueryBuilder;
7
use Knp\Component\Pager\PaginatorInterface;
8
9
class PaginatorAdapter implements PaginatorInterface
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
10
{
11
    protected $paginator;
12
13 19
    public function __construct(PaginatorInterface $paginator)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
14
    {
15 19
        $this->paginator = $paginator;
16
    }
17
18 19
    public function paginate($target, $page = 1, $limit = 10, array $options = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
19
    {
20 19
        if (!$target instanceof QueryBuilder) {
21 2
            throw new \InvalidArgumentException();
22
        }
23
24
        // wrap-queriesが未定義またはfalseの場合はデフォルトのページネータで処理.
25 17
        if (empty($options['wrap-queries'])) {
26 9
            return $this->paginator->paginate($target, $page, $limit, $options);
27
        }
28
29
        // 総件数の取得.
30 8
        $platform = $target->getEntityManager()->getConnection()->getDatabasePlatform();
31 8
        $rsm = new Query\ResultSetMapping();
32 8
        $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count');
33
34
        // `wrap-queries: true`時の総件数取得クエリを再現するため、CountOutputWalkerを使う
35
        // CountOutputWalkerはdoctrine orm 2.5.xのコードを利用(2.4.xの不具合が修正されてる)
36 8
        $query = $target->getQuery();
37 8
        $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Eccube\Doctrine\ORM\Tools\Pagination\CountOutputWalker');
38 8
        $query->setResultSetMapping($rsm);
39 8
        $totalCount = $query->getSingleScalarResult();
40
41
        // limit, offsetの設定
42 8
        $offset = abs($page - 1) * $limit;
43 8
        $target->setMaxResults($limit);
44 8
        $target->setFirstResult($offset);
45
46
        // pagenatorを空で作成し, 各オプションを設定する
47 8
        $pagination = $this->paginator->paginate(array());
48 8
        $pagination->setCurrentPageNumber($page);
49 8
        $pagination->setItemNumberPerPage($limit);
50 8
        $pagination->setItems($target->getQuery()->getResult());
51 8
        $pagination->setTotalItemCount($totalCount);
52
53 8
        return $pagination;
54
    }
55
}