Passed
Pull Request — 2.6 (#7821)
by Marco
07:55
created

Paginator::useOutputWalker()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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