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