Completed
Pull Request — 2.6 (#7903)
by Gabriel
532:29 queued 524:33
created

Paginator::getIterator()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 50
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 34
c 2
b 0
f 0
dl 0
loc 50
rs 9.376
ccs 32
cts 32
cp 1
cc 4
nc 5
nop 0
crap 4
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ORM\Tools\Pagination;
21
22
use Doctrine\ORM\EntityManagerInterface;
23
use Doctrine\ORM\Mapping\MappingException;
24
use Doctrine\ORM\NoResultException;
25
use Doctrine\ORM\Query;
26
use Doctrine\ORM\Query\Parser;
27
use Doctrine\ORM\Query\ResultSetMapping;
28
use Doctrine\ORM\QueryBuilder;
29
use function array_map;
30
31
/**
32
 * The paginator can handle various complex scenarios with DQL.
33
 *
34
 * @author Pablo Díez <[email protected]>
35
 * @author Benjamin Eberlei <[email protected]>
36
 * @license New BSD
37
 */
38
class Paginator implements \Countable, \IteratorAggregate
39
{
40
    /**
41
     * @var Query
42
     */
43
    private $query;
44
45
    /**
46
     * @var bool
47
     */
48
    private $fetchJoinCollection;
49
50
    /**
51
     * @var bool|null
52
     */
53
    private $useOutputWalkers;
54
55
    /**
56
     * @var int
57
     */
58
    private $count;
59
60
    /**
61
     * Constructor.
62
     *
63
     * @param Query|QueryBuilder $query               A Doctrine ORM query or query builder.
64
     * @param boolean            $fetchJoinCollection Whether the query joins a collection (true by default).
65
     */
66 111
    public function __construct($query, $fetchJoinCollection = true)
67
    {
68 111
        if ($query instanceof QueryBuilder) {
69 2
            $query = $query->getQuery();
70
        }
71
72 111
        $this->query = $query;
73 111
        $this->fetchJoinCollection = (bool) $fetchJoinCollection;
74 111
    }
75
76
    /**
77
     * Returns the query.
78
     *
79
     * @return Query
80
     */
81
    public function getQuery()
82
    {
83
        return $this->query;
84
    }
85
86
    /**
87
     * Returns whether the query joins a collection.
88
     *
89
     * @return boolean Whether the query joins a collection.
90
     */
91
    public function getFetchJoinCollection()
92
    {
93
        return $this->fetchJoinCollection;
94
    }
95
96
    /**
97
     * Returns whether the paginator will use an output walker.
98
     *
99
     * @return bool|null
100
     */
101
    public function getUseOutputWalkers()
102
    {
103
        return $this->useOutputWalkers;
104
    }
105
106
    /**
107
     * Sets whether the paginator will use an output walker.
108
     *
109
     * @param bool|null $useOutputWalkers
110
     *
111
     * @return $this
112
     */
113 98
    public function setUseOutputWalkers($useOutputWalkers)
114
    {
115 98
        $this->useOutputWalkers = $useOutputWalkers;
116
117 98
        return $this;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 19
    public function count()
124
    {
125 19
        if ($this->count === null) {
126
            try {
127 19
                $this->count = array_sum(array_map('current', $this->getCountQuery()->getScalarResult()));
128 2
            } catch (NoResultException $e) {
129
                $this->count = 0;
130
            }
131
        }
132
133 17
        return $this->count;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139 98
    public function getIterator()
140
    {
141 98
        $offset = $this->query->getFirstResult();
142 98
        $length = $this->query->getMaxResults();
143
144 98
        if ($this->fetchJoinCollection) {
145 71
            $subQuery = $this->cloneQuery($this->query);
146
147 71
            if ($this->useOutputWalker($subQuery)) {
148 43
                $subQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class);
149
            } else {
150 28
                $this->appendTreeWalker($subQuery, LimitSubqueryWalker::class);
151 28
                $this->unbindUnusedQueryParams($subQuery);
152
            }
153
154 68
            $subQuery->setFirstResult($offset)->setMaxResults($length);
155
156 68
            $foundIdRows = $subQuery->getScalarResult();
157
158
            // don't do this for an empty id array
159 68
            if ($foundIdRows === []) {
160 2
                return new \ArrayIterator([]);
161
            }
162
163 67
            $em           = $subQuery->getEntityManager();
164 67
            $connection   = $em->getConnection();
165 67
            $idType       = $this->getIdentifiersQueryScalarResultType($subQuery, $em);
166 67
            $whereInQuery = $this->cloneQuery($this->query);
167
            $ids          = array_map(static function (array $row) use ($idType, $connection) {
168 67
                return $connection->convertToPHPValue(current($row), $idType);
169 67
            }, $foundIdRows);
170
171 67
            $this->appendTreeWalker($whereInQuery, WhereInWalker::class);
172 67
            $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids));
173 67
            $whereInQuery->setFirstResult(null)->setMaxResults(null);
174 67
            $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids);
175 67
            $whereInQuery->setCacheable($this->query->isCacheable());
176 67
            $whereInQuery->expireQueryCache();
177
178 67
            $result = $whereInQuery->getResult($this->query->getHydrationMode());
179
        } else {
180 27
            $result = $this->cloneQuery($this->query)
181 27
                ->setMaxResults($length)
182 27
                ->setFirstResult($offset)
183 27
                ->setCacheable($this->query->isCacheable())
184 27
                ->getResult($this->query->getHydrationMode())
185
            ;
186
        }
187
188 93
        return new \ArrayIterator($result);
189
    }
190
191
    /**
192
     * Clones a query.
193
     *
194
     * @param Query $query The query.
195
     *
196
     * @return Query The cloned query.
197
     */
198 111
    private function cloneQuery(Query $query)
199
    {
200
        /* @var $cloneQuery Query */
201 111
        $cloneQuery = clone $query;
202
203 111
        $cloneQuery->setParameters(clone $query->getParameters());
204 111
        $cloneQuery->setCacheable(false);
205
206 111
        foreach ($query->getHints() as $name => $value) {
207 4
            $cloneQuery->setHint($name, $value);
208
        }
209
210 111
        return $cloneQuery;
211
    }
212
213
    /**
214
     * Determines whether to use an output walker for the query.
215
     *
216
     * @param Query $query The query.
217
     *
218
     * @return bool
219
     */
220 85
    private function useOutputWalker(Query $query)
221
    {
222 85
        if ($this->useOutputWalkers === null) {
223 13
            return (bool) $query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER) === false;
224
        }
225
226 72
        return $this->useOutputWalkers;
227
    }
228
229
    /**
230
     * Appends a custom tree walker to the tree walkers hint.
231
     *
232
     * @param Query  $query
233
     * @param string $walkerClass
234
     */
235 78
    private function appendTreeWalker(Query $query, $walkerClass)
236
    {
237 78
        $hints = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
238
239 78
        if ($hints === false) {
240 76
            $hints = [];
241
        }
242
243 78
        $hints[] = $walkerClass;
244 78
        $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $hints);
245 78
    }
246
247
    /**
248
     * Returns Query prepared to count.
249
     *
250
     * @return Query
251
     */
252 19
    private function getCountQuery()
253
    {
254
        /* @var $countQuery Query */
255 19
        $countQuery = $this->cloneQuery($this->query);
256
257 19
        if ( ! $countQuery->hasHint(CountWalker::HINT_DISTINCT)) {
258 19
            $countQuery->setHint(CountWalker::HINT_DISTINCT, true);
259
        }
260
261 19
        if ($this->useOutputWalker($countQuery)) {
262 9
            $platform = $countQuery->getEntityManager()->getConnection()->getDatabasePlatform(); // law of demeter win
263
264 9
            $rsm = new ResultSetMapping();
265 9
            $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count');
266
267 9
            $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class);
268 9
            $countQuery->setResultSetMapping($rsm);
269
        } else {
270 11
            $this->appendTreeWalker($countQuery, CountWalker::class);
271 11
            $this->unbindUnusedQueryParams($countQuery);
272
        }
273
274 17
        $countQuery->setFirstResult(null)->setMaxResults(null);
275
276 17
        return $countQuery;
277
    }
278
279 35
    private function unbindUnusedQueryParams(Query $query): void
280
    {
281 35
        $parser            = new Parser($query);
282 35
        $parameterMappings = $parser->parse()->getParameterMappings();
283
        /* @var $parameters \Doctrine\Common\Collections\Collection|\Doctrine\ORM\Query\Parameter[] */
284 30
        $parameters        = $query->getParameters();
285
286 30
        foreach ($parameters as $key => $parameter) {
287 4
            $parameterName = $parameter->getName();
288
289 4
            if ( ! (isset($parameterMappings[$parameterName]) || array_key_exists($parameterName, $parameterMappings))) {
290 4
                unset($parameters[$key]);
291
            }
292
        }
293
294 30
        $query->setParameters($parameters);
295 30
    }
296
297
    /**
298
     * Parses a query that is supposed to fetch a set of entity identifier only,
299
     * and retrieves the type of said identifier.
300
     *
301
     * @throws MappingException If metadata couldn't be loaded, or if there isn't a single
302
     *                          identifier for the given query.
303
     */
304 67
    private function getIdentifiersQueryScalarResultType(
305
        Query $query,
306
        EntityManagerInterface $em
307
    ) : ?string {
308 67
        $rsm = (new Parser($query))
309 67
            ->parse()
310 67
            ->getResultSetMapping();
311
312 67
        assert($rsm !== null);
313 67
        assert($rsm->isSelect);
314
315 67
        return $rsm->getTypeOfSelectionRootSingleIdentifierColumn($em);
316
    }
317
}
318