Completed
Push — master ( 6b9dc2...7d0bd2 )
by Kevin
02:21
created

RSMQueryResult::take()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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