Completed
Push — master ( d259d9...b8aac0 )
by Kevin
02:33
created

RSMQueryResult::take()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.4285
cc 1
eloc 9
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Zenstruck\Porpaginas\Doctrine;
4
5
use Doctrine\DBAL\Query\QueryBuilder;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Doctrine\ORM\Query\ResultSetMappingBuilder;
8
use Zenstruck\Porpaginas\Callback\CallbackPage;
9
use Zenstruck\Porpaginas\Result;
10
11
/**
12
 * @author Florian Klein <[email protected]>
13
 * @author Kevin Bond <[email protected]>
14
 */
15
final class RSMQueryResult implements Result
16
{
17
    private $em;
18
    private $rsm;
19
    private $qb;
20
    private $queryBuilderResult;
21
22
    /**
23
     * @param EntityManagerInterface  $em
24
     * @param ResultSetMappingBuilder $rsm
25
     * @param QueryBuilder            $qb
26
     * @param callable|null           $countQueryBuilderModifier
27
     */
28 6
    public function __construct(EntityManagerInterface $em, ResultSetMappingBuilder $rsm, QueryBuilder $qb, callable $countQueryBuilderModifier = null)
29
    {
30 6
        $this->em = $em;
31 6
        $this->rsm = $rsm;
32 6
        $this->qb = $qb;
33 6
        $this->queryBuilderResult = new DBALQueryBuilderResult($qb, $countQueryBuilderModifier);
34 6
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 4
    public function take($offset, $limit)
40
    {
41 4
        $qb = clone $this->qb;
42 4
        $results = function ($offset, $limit) use ($qb) {
43 4
            $qb->setFirstResult($offset)
44 4
                ->setMaxResults($limit);
45
46 4
            $query = $this->em->createNativeQuery($qb->getSql(), $this->rsm);
47 4
            $query->setParameters($qb->getParameters());
48
49 4
            return $query->execute();
50 4
        };
51
52 4
        return new CallbackPage($results, [$this, 'count'], $offset, $limit);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 2
    public function count()
59
    {
60 2
        return $this->queryBuilderResult->count();
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 1
    public function getIterator()
67
    {
68 1
        $query = $this->em->createNativeQuery($this->qb->getSql(), $this->rsm);
69 1
        $query->setParameters($this->qb->getParameters());
70
71 1
        return $query->iterate();
72
    }
73
}
74