Passed
Pull Request — 2.6 (#7821)
by Marco
09:17
created

Paginator::getIterator()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 44
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 4

Importance

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