Passed
Pull Request — 2.6 (#7903)
by Gabriel
07:02
created

Paginator::cloneQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

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