Passed
Pull Request — 2.6 (#7821)
by Marco
11:52
created

Paginator   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 277
Duplicated Lines 0 %

Test Coverage

Coverage 93.07%

Importance

Changes 0
Metric Value
eloc 94
c 0
b 0
f 0
dl 0
loc 277
rs 10
ccs 94
cts 101
cp 0.9307
wmc 27

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getFetchJoinCollection() 0 3 1
A appendTreeWalker() 0 10 2
A __construct() 0 8 2
A getIterator() 0 49 4
A unbindUnusedQueryParams() 0 16 4
A useOutputWalker() 0 7 2
A getUseOutputWalkers() 0 3 1
A getCountQuery() 0 25 3
A cloneQuery() 0 13 2
A getIdentifiersQueryScalarResultType() 0 12 1
A getQuery() 0 3 1
A setUseOutputWalkers() 0 5 1
A count() 0 11 3
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\Query\Parser;
25
use Doctrine\ORM\QueryBuilder;
26
use Doctrine\ORM\Query;
27
use Doctrine\ORM\Query\ResultSetMapping;
28
use Doctrine\ORM\NoResultException;
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 109
    public function __construct($query, $fetchJoinCollection = true)
69
    {
70 109
        if ($query instanceof QueryBuilder) {
71 1
            $query = $query->getQuery();
72
        }
73
74 109
        $this->query = $query;
75 109
        $this->fetchJoinCollection = (bool) $fetchJoinCollection;
76 109
    }
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 97
    public function setUseOutputWalkers($useOutputWalkers)
116
    {
117 97
        $this->useOutputWalkers = $useOutputWalkers;
118
119 97
        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 96
    public function getIterator()
142
    {
143 96
        $offset = $this->query->getFirstResult();
144 96
        $length = $this->query->getMaxResults();
145
146 96
        if ($this->fetchJoinCollection) {
147 69
            $subQuery = $this->cloneQuery($this->query);
148
149 69
            if ($this->useOutputWalker($subQuery)) {
150 42
                $subQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class);
151
            } else {
152 27
                $this->appendTreeWalker($subQuery, LimitSubqueryWalker::class);
153 27
                $this->unbindUnusedQueryParams($subQuery);
154
            }
155
156 66
            $subQuery->setFirstResult($offset)->setMaxResults($length);
157
158 66
            $foundIdRows = $subQuery->getScalarResult();
159
160
            // don't do this for an empty id array
161 66
            if ($foundIdRows === []) {
162 2
                return new \ArrayIterator([]);
163
            }
164
165 65
            $whereInQuery = $this->cloneQuery($this->query);
166 65
            $em           = $subQuery->getEntityManager();
167 65
            $connection   = $em->getConnection();
168 65
            $idType       = $this->getIdentifiersQueryScalarResultType($subQuery, $em);
169
            $ids          = array_map(static function (array $row) use ($connection, $idType) {
170 65
                return $connection->convertToDatabaseValue(current($row), $idType);
171 65
            }, $foundIdRows);
172
173 65
            $this->appendTreeWalker($whereInQuery, WhereInWalker::class);
174 65
            $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids));
175 65
            $whereInQuery->setFirstResult(null)->setMaxResults(null);
176 65
            $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids);
177 65
            $whereInQuery->setCacheable($this->query->isCacheable());
178
179 65
            $result = $whereInQuery->getResult($this->query->getHydrationMode());
180
        } else {
181 27
            $result = $this->cloneQuery($this->query)
182 27
                ->setMaxResults($length)
183 27
                ->setFirstResult($offset)
184 27
                ->setCacheable($this->query->isCacheable())
185 27
                ->getResult($this->query->getHydrationMode())
186
            ;
187
        }
188
189 91
        return new \ArrayIterator($result);
190
    }
191
192
    /**
193
     * Clones a query.
194
     *
195
     * @param Query $query The query.
196
     *
197
     * @return Query The cloned query.
198
     */
199 109
    private function cloneQuery(Query $query)
200
    {
201
        /* @var $cloneQuery Query */
202 109
        $cloneQuery = clone $query;
203
204 109
        $cloneQuery->setParameters(clone $query->getParameters());
205 109
        $cloneQuery->setCacheable(false);
206
207 109
        foreach ($query->getHints() as $name => $value) {
208 3
            $cloneQuery->setHint($name, $value);
209
        }
210
211 109
        return $cloneQuery;
212
    }
213
214
    /**
215
     * Determines whether to use an output walker for the query.
216
     *
217
     * @param Query $query The query.
218
     *
219
     * @return bool
220
     */
221 83
    private function useOutputWalker(Query $query)
222
    {
223 83
        if ($this->useOutputWalkers === null) {
224 12
            return (bool) $query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER) === false;
225
        }
226
227 71
        return $this->useOutputWalkers;
228
    }
229
230
    /**
231
     * Appends a custom tree walker to the tree walkers hint.
232
     *
233
     * @param Query  $query
234
     * @param string $walkerClass
235
     */
236 76
    private function appendTreeWalker(Query $query, $walkerClass)
237
    {
238 76
        $hints = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
239
240 76
        if ($hints === false) {
241 75
            $hints = [];
242
        }
243
244 76
        $hints[] = $walkerClass;
245 76
        $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $hints);
246 76
    }
247
248
    /**
249
     * Returns Query prepared to count.
250
     *
251
     * @return Query
252
     */
253 18
    private function getCountQuery()
254
    {
255
        /* @var $countQuery Query */
256 18
        $countQuery = $this->cloneQuery($this->query);
257
258 18
        if ( ! $countQuery->hasHint(CountWalker::HINT_DISTINCT)) {
259 18
            $countQuery->setHint(CountWalker::HINT_DISTINCT, true);
260
        }
261
262 18
        if ($this->useOutputWalker($countQuery)) {
263 9
            $platform = $countQuery->getEntityManager()->getConnection()->getDatabasePlatform(); // law of demeter win
264
265 9
            $rsm = new ResultSetMapping();
266 9
            $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count');
267
268 9
            $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class);
269 9
            $countQuery->setResultSetMapping($rsm);
270
        } else {
271 10
            $this->appendTreeWalker($countQuery, CountWalker::class);
272 10
            $this->unbindUnusedQueryParams($countQuery);
273
        }
274
275 16
        $countQuery->setFirstResult(null)->setMaxResults(null);
276
277 16
        return $countQuery;
278
    }
279
280 34
    private function unbindUnusedQueryParams(Query $query): void
281
    {
282 34
        $parser            = new Parser($query);
283 34
        $parameterMappings = $parser->parse()->getParameterMappings();
284
        /* @var $parameters \Doctrine\Common\Collections\Collection|\Doctrine\ORM\Query\Parameter[] */
285 29
        $parameters        = $query->getParameters();
286
287 29
        foreach ($parameters as $key => $parameter) {
288 4
            $parameterName = $parameter->getName();
289
290 4
            if ( ! (isset($parameterMappings[$parameterName]) || array_key_exists($parameterName, $parameterMappings))) {
291 4
                unset($parameters[$key]);
292
            }
293
        }
294
295 29
        $query->setParameters($parameters);
296 29
    }
297
298
    /**
299
     * Parses a query that is supposed to fetch a set of entity identifier only,
300
     * and retrieves the type of said identifier.
301
     *
302
     * @throws MappingException If metadata couldn't be loaded, or if there isn't a single
303
     *                          identifier for the given query.
304
     */
305 65
    private function getIdentifiersQueryScalarResultType(
306
        Query $query,
307
        EntityManagerInterface $em
308
    ) : ?string {
309 65
        $rsm = (new Parser($query))
310 65
            ->parse()
311 65
            ->getResultSetMapping();
312
313 65
        assert($rsm !== null);
314 65
        assert($rsm->isSelect);
315
316 65
        return $rsm->getTypeOfSelectionRootSingleIdentifierColumn($em);
317
    }
318
}
319