Completed
Push — master ( 7d0bd2...0a4f4d )
by Kevin
02:13
created

ORMQueryResult::createPaginator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 3
cts 3
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Zenstruck\Porpaginas\Doctrine\ORM;
4
5
use Doctrine\ORM\Query;
6
use Doctrine\ORM\QueryBuilder;
7
use Doctrine\ORM\Tools\Pagination\Paginator;
8
use Zenstruck\Porpaginas\Callback\CallbackPage;
9
use Zenstruck\Porpaginas\Result;
10
11
final class ORMQueryResult implements Result
12
{
13
    private $query;
14
    private $fetchCollection;
15
    private $count;
16
17
    /**
18
     * @param Query|QueryBuilder $query
19
     * @param bool               $fetchCollection
20
     */
21
    public function __construct($query, $fetchCollection = true)
22 12
    {
23
        if ($query instanceof QueryBuilder) {
24 12
            $query = $query->getQuery();
25 6
        }
26 6
27
        $this->query = $query;
28 12
        $this->fetchCollection = $fetchCollection;
29 12
    }
30 12
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function take($offset, $limit)
35 8
    {
36
        $results = function ($offset, $limit) {
37 8
            return iterator_to_array($this->createPaginator($offset, $limit));
38
        };
39
40
        return new CallbackPage($results, [$this, 'count'], $offset, $limit);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 8
    public function count()
47
    {
48
        if (null !== $this->count) {
49
            return $this->count;
50
        }
51
52 2
        return $this->count = count($this->createPaginator(0, 1));
53
    }
54 2
55
    /**
56
     * {@inheritdoc}
57
     */
58 2
    public function getIterator()
59
    {
60
        return $this->query->iterate();
61
    }
62
63
    /**
64 2
     * @param int $offset
65
     * @param int $limit
66 2
     *
67 2
     * @return Paginator
68 2
     */
69 2
    private function createPaginator($offset, $limit)
70
    {
71 2
        $query = clone $this->query;
72
        $query->setParameters($this->query->getParameters());
73
74
        foreach ($this->query->getHints() as $name => $value) {
75
            $query->setHint($name, $value);
76
        }
77
78
        $query->setFirstResult($offset)->setMaxResults($limit);
79
80 10
        return new Paginator($query, $this->fetchCollection);
81
    }
82
}
83