Passed
Pull Request — master (#7222)
by
unknown
09:54
created

Paginator   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 248
Duplicated Lines 0 %

Test Coverage

Coverage 90.91%

Importance

Changes 0
Metric Value
dl 0
loc 248
rs 10
c 0
b 0
f 0
ccs 80
cts 88
cp 0.9091
wmc 27

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getFetchJoinCollection() 0 3 1
A __construct() 0 8 2
A getUseOutputWalkers() 0 3 1
A getQuery() 0 3 1
A setUseOutputWalkers() 0 5 1
A count() 0 11 3
A appendTreeWalker() 0 10 2
B getIterator() 0 43 4
A getPagesCount() 0 5 2
A useOutputWalker() 0 7 2
B getCountQuery() 0 40 6
A cloneQuery() 0 13 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Tools\Pagination;
6
7
use Doctrine\Common\Collections\Collection;
8
use Doctrine\DBAL\Types\Type;
9
use Doctrine\ORM\NoResultException;
10
use Doctrine\ORM\Query;
11
use Doctrine\ORM\Query\Parameter;
12
use Doctrine\ORM\Query\Parser;
13
use Doctrine\ORM\Query\ResultSetMapping;
14
use Doctrine\ORM\QueryBuilder;
15
use function array_key_exists;
16
use function array_map;
17
use function array_sum;
18
use function count;
19
20
/**
21
 * The paginator can handle various complex scenarios with DQL.
22
 */
23
class Paginator implements \Countable, \IteratorAggregate
24
{
25
    /** @var Query */
26
    private $query;
27
28
    /** @var bool */
29
    private $fetchJoinCollection;
30
31
    /** @var bool|null */
32
    private $useOutputWalkers;
33
34
    /** @var int */
35
    private $count;
36
37
    /**
38
     * @param Query|QueryBuilder $query               A Doctrine ORM query or query builder.
39
     * @param bool               $fetchJoinCollection Whether the query joins a collection (true by default).
40
     */
41 107
    public function __construct($query, $fetchJoinCollection = true)
42
    {
43 107
        if ($query instanceof QueryBuilder) {
44
            $query = $query->getQuery();
45
        }
46
47 107
        $this->query               = $query;
48 107
        $this->fetchJoinCollection = (bool) $fetchJoinCollection;
49 107
    }
50
51
    /**
52
     * Returns the query.
53
     *
54
     * @return Query
55
     */
56
    public function getQuery()
57
    {
58
        return $this->query;
59
    }
60
61
    /**
62
     * Returns whether the query joins a collection.
63
     *
64
     * @return bool Whether the query joins a collection.
65
     */
66
    public function getFetchJoinCollection()
67
    {
68
        return $this->fetchJoinCollection;
69
    }
70
71
    /**
72
     * Returns whether the paginator will use an output walker.
73
     *
74
     * @return bool|null
75
     */
76
    public function getUseOutputWalkers()
77
    {
78
        return $this->useOutputWalkers;
79
    }
80
81
    /**
82
     * Sets whether the paginator will use an output walker.
83
     *
84
     * @param bool|null $useOutputWalkers
85
     *
86
     * @return $this
87
     */
88 94
    public function setUseOutputWalkers($useOutputWalkers)
89
    {
90 94
        $this->useOutputWalkers = $useOutputWalkers;
91
92 94
        return $this;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98 18
    public function count()
99
    {
100 18
        if ($this->count === null) {
101
            try {
102 18
                $this->count = array_sum(array_map('current', $this->getCountQuery()->getScalarResult()));
103 2
            } catch (NoResultException $e) {
104
                $this->count = 0;
105
            }
106
        }
107
108 16
        return $this->count;
109
    }
110
    
111
    /**
112
     * Returns number of pages
113
     *
114
     * @return int|null
115
     */
116 2
    public function getPagesCount()
117
    {
118 2
        $maxResults = $this->query->getMaxResults();
119
120 2
        return $maxResults !== null ? (int) ceil($this->count() / $maxResults) : null;
0 ignored issues
show
introduced by
Function ceil() should not be referenced via a fallback global name, but via a use statement.
Loading history...
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 92
    public function getIterator()
127
    {
128 92
        $offset = $this->query->getFirstResult();
129 92
        $length = $this->query->getMaxResults();
130
131 92
        if ($this->fetchJoinCollection) {
132 65
            $subQuery = $this->cloneQuery($this->query);
133
134 65
            if ($this->useOutputWalker($subQuery)) {
135 41
                $subQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class);
136
            } else {
137 24
                $this->appendTreeWalker($subQuery, LimitSubqueryWalker::class);
138
            }
139
140 65
            $subQuery->setFirstResult($offset)->setMaxResults($length);
141
142 65
            $ids = array_map('current', $subQuery->getScalarResult());
143
144 62
            $whereInQuery = $this->cloneQuery($this->query);
145
146
            // don't do this for an empty id array
147 62
            if (count($ids) === 0) {
148 1
                return new \ArrayIterator([]);
149
            }
150
151 62
            $this->appendTreeWalker($whereInQuery, WhereInWalker::class);
152
153 62
            $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids));
154 62
            $whereInQuery->setFirstResult(null)->setMaxResults(null);
155 62
            $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids);
156 62
            $whereInQuery->setCacheable($this->query->isCacheable());
157
158 62
            $result = $whereInQuery->getResult($this->query->getHydrationMode());
159
        } else {
160 27
            $result = $this->cloneQuery($this->query)
161 27
                ->setMaxResults($length)
162 27
                ->setFirstResult($offset)
163 27
                ->setCacheable($this->query->isCacheable())
164 27
                ->getResult($this->query->getHydrationMode())
165
            ;
166
        }
167
168 89
        return new \ArrayIterator($result);
169
    }
170
171
    /**
172
     * Clones a query.
173
     *
174
     * @param Query $query The query.
175
     *
176
     * @return Query The cloned query.
177
     */
178 107
    private function cloneQuery(Query $query)
179
    {
180
        /** @var Query $cloneQuery */
181 107
        $cloneQuery = clone $query;
182
183 107
        $cloneQuery->setParameters(clone $query->getParameters());
184 107
        $cloneQuery->setCacheable(false);
185
186 107
        foreach ($query->getHints() as $name => $value) {
187 3
            $cloneQuery->setHint($name, $value);
188
        }
189
190 107
        return $cloneQuery;
191
    }
192
193
    /**
194
     * Determines whether to use an output walker for the query.
195
     *
196
     * @param Query $query The query.
197
     *
198
     * @return bool
199
     */
200 81
    private function useOutputWalker(Query $query)
201
    {
202 81
        if ($this->useOutputWalkers === null) {
203 13
            return (bool) $query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER) === false;
204
        }
205
206 68
        return $this->useOutputWalkers;
207
    }
208
209
    /**
210
     * Appends a custom tree walker to the tree walkers hint.
211
     *
212
     * @param string $walkerClass
213
     */
214 72
    private function appendTreeWalker(Query $query, $walkerClass)
215
    {
216 72
        $hints = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
217
218 72
        if ($hints === false) {
219 71
            $hints = [];
220
        }
221
222 72
        $hints[] = $walkerClass;
223 72
        $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $hints);
224 72
    }
225
226
    /**
227
     * Returns Query prepared to count.
228
     *
229
     * @return Query
230
     */
231 18
    private function getCountQuery()
232
    {
233
        /** @var Query $countQuery */
234 18
        $countQuery = $this->cloneQuery($this->query);
235
236 18
        if (! $countQuery->hasHint(CountWalker::HINT_DISTINCT)) {
237 18
            $countQuery->setHint(CountWalker::HINT_DISTINCT, true);
238
        }
239
240 18
        if ($this->useOutputWalker($countQuery)) {
241 11
            $platform = $countQuery->getEntityManager()->getConnection()->getDatabasePlatform(); // law of demeter win
242
243 11
            $rsm = new ResultSetMapping();
244
245 11
            $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count', Type::getType('integer'));
246
247 11
            $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class);
248 11
            $countQuery->setResultSetMapping($rsm);
249
        } else {
250 8
            $this->appendTreeWalker($countQuery, CountWalker::class);
251
        }
252
253 18
        $countQuery->setFirstResult(null)->setMaxResults(null);
254
255 18
        $parser            = new Parser($countQuery);
256 18
        $parameterMappings = $parser->parse()->getParameterMappings();
257
        /** @var Collection|Parameter[] $parameters */
258 16
        $parameters = $countQuery->getParameters();
259
260 16
        foreach ($parameters as $key => $parameter) {
261 2
            $parameterName = $parameter->getName();
262
263 2
            if (! (isset($parameterMappings[$parameterName]) || array_key_exists($parameterName, $parameterMappings))) {
264 2
                unset($parameters[$key]);
265
            }
266
        }
267
268 16
        $countQuery->setParameters($parameters);
269
270 16
        return $countQuery;
271
    }
272
}
273