Passed
Push — master ( ad5014...e80cd7 )
by Marco
15:42
created

Query::__clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1
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;
21
22
use Doctrine\DBAL\LockMode;
23
use Doctrine\ORM\Query\Exec\AbstractSqlExecutor;
24
use Doctrine\ORM\Query\Parser;
25
use Doctrine\ORM\Query\ParserResult;
26
use Doctrine\ORM\Query\QueryException;
27
use Doctrine\ORM\Mapping\ClassMetadata;
28
use Doctrine\ORM\Query\ParameterTypeInferer;
29
use Doctrine\Common\Collections\ArrayCollection;
30
31
/**
32
 * A Query object represents a DQL query.
33
 *
34
 * @since   1.0
35
 * @author  Guilherme Blanco <[email protected]>
36
 * @author  Konsta Vesterinen <[email protected]>
37
 * @author  Roman Borschel <[email protected]>
38
 */
39
final class Query extends AbstractQuery
40
{
41
    /**
42
     * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.
43
     */
44
    const STATE_CLEAN  = 1;
45
46
    /**
47
     * A query object is in state DIRTY when it has DQL parts that have not yet been
48
     * parsed/processed. This is automatically defined as DIRTY when addDqlQueryPart
49
     * is called.
50
     */
51
    const STATE_DIRTY = 2;
52
53
    /* Query HINTS */
54
55
    /**
56
     * The refresh hint turns any query into a refresh query with the result that
57
     * any local changes in entities are overridden with the fetched values.
58
     *
59
     * @var string
60
     */
61
    const HINT_REFRESH = 'doctrine.refresh';
62
63
    /**
64
     * @var string
65
     */
66
    const HINT_CACHE_ENABLED = 'doctrine.cache.enabled';
67
68
    /**
69
     * @var string
70
     */
71
    const HINT_CACHE_EVICT = 'doctrine.cache.evict';
72
73
    /**
74
     * Internal hint: is set to the proxy entity that is currently triggered for loading
75
     *
76
     * @var string
77
     */
78
    const HINT_REFRESH_ENTITY = 'doctrine.refresh.entity';
79
80
    /**
81
     * The forcePartialLoad query hint forces a particular query to return
82
     * partial objects.
83
     *
84
     * @var string
85
     * @todo Rename: HINT_OPTIMIZE
86
     */
87
    const HINT_FORCE_PARTIAL_LOAD = 'doctrine.forcePartialLoad';
88
89
    /**
90
     * The includeMetaColumns query hint causes meta columns like foreign keys and
91
     * discriminator columns to be selected and returned as part of the query result.
92
     *
93
     * This hint does only apply to non-object queries.
94
     *
95
     * @var string
96
     */
97
    const HINT_INCLUDE_META_COLUMNS = 'doctrine.includeMetaColumns';
98
99
    /**
100
     * An array of class names that implement \Doctrine\ORM\Query\TreeWalker and
101
     * are iterated and executed after the DQL has been parsed into an AST.
102
     *
103
     * @var string
104
     */
105
    const HINT_CUSTOM_TREE_WALKERS = 'doctrine.customTreeWalkers';
106
107
    /**
108
     * A string with a class name that implements \Doctrine\ORM\Query\TreeWalker
109
     * and is used for generating the target SQL from any DQL AST tree.
110
     *
111
     * @var string
112
     */
113
    const HINT_CUSTOM_OUTPUT_WALKER = 'doctrine.customOutputWalker';
114
115
    //const HINT_READ_ONLY = 'doctrine.readOnly';
116
117
    /**
118
     * @var string
119
     */
120
    const HINT_INTERNAL_ITERATION = 'doctrine.internal.iteration';
121
122
    /**
123
     * @var string
124
     */
125
    const HINT_LOCK_MODE = 'doctrine.lockMode';
126
127
    /**
128
     * The current state of this query.
129
     *
130
     * @var integer
131
     */
132
    private $_state = self::STATE_CLEAN;
133
134
    /**
135
     * A snapshot of the parameter types the query was parsed with.
136
     *
137
     * @var array
138
     */
139
    private $_parsedTypes = [];
140
141
    /**
142
     * Cached DQL query.
143
     *
144
     * @var string
145
     */
146
    private $_dql = null;
147
148
    /**
149
     * The parser result that holds DQL => SQL information.
150
     *
151
     * @var \Doctrine\ORM\Query\ParserResult
152
     */
153
    private $_parserResult;
154
155
    /**
156
     * The first result to return (the "offset").
157
     *
158
     * @var integer
159
     */
160
    private $_firstResult = null;
161
162
    /**
163
     * The maximum number of results to return (the "limit").
164
     *
165
     * @var integer
166
     */
167
    private $_maxResults = null;
168
169
    /**
170
     * The cache driver used for caching queries.
171
     *
172
     * @var \Doctrine\Common\Cache\Cache|null
173
     */
174
    private $_queryCache;
175
176
    /**
177
     * Whether or not expire the query cache.
178
     *
179
     * @var boolean
180
     */
181
    private $_expireQueryCache = false;
182
183
    /**
184
     * The query cache lifetime.
185
     *
186
     * @var int
187
     */
188
    private $_queryCacheTTL;
189
190
    /**
191
     * Whether to use a query cache, if available. Defaults to TRUE.
192
     *
193
     * @var boolean
194
     */
195
    private $_useQueryCache = true;
196
197
    /**
198
     * Gets the SQL query/queries that correspond to this DQL query.
199
     *
200
     * @return mixed The built sql query or an array of all sql queries.
201
     *
202
     * @override
203
     */
204 332
    public function getSQL()
205
    {
206 332
        return $this->_parse()->getSqlExecutor()->getSqlStatements();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->_parse()->...()->getSqlStatements(); (array) is incompatible with the return type declared by the abstract method Doctrine\ORM\AbstractQuery::getSQL of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
207
    }
208
209
    /**
210
     * Returns the corresponding AST for this DQL query.
211
     *
212
     * @return \Doctrine\ORM\Query\AST\SelectStatement |
213
     *         \Doctrine\ORM\Query\AST\UpdateStatement |
214
     *         \Doctrine\ORM\Query\AST\DeleteStatement
215
     */
216 2
    public function getAST()
217
    {
218 2
        $parser = new Parser($this);
219
220 2
        return $parser->getAST();
221
    }
222
223
    /**
224
     * {@inheritdoc}
225
     */
226 429
    protected function getResultSetMapping()
227
    {
228
        // parse query or load from cache
229 429
        if ($this->_resultSetMapping === null) {
230 38
            $this->_resultSetMapping = $this->_parse()->getResultSetMapping();
231
        }
232
233 426
        return $this->_resultSetMapping;
234
    }
235
236
    /**
237
     * Parses the DQL query, if necessary, and stores the parser result.
238
     *
239
     * Note: Populates $this->_parserResult as a side-effect.
240
     *
241
     * @return \Doctrine\ORM\Query\ParserResult
242
     */
243 747
    private function _parse()
244
    {
245 747
        $types = [];
246
247 747
        foreach ($this->parameters as $parameter) {
248
            /** @var Query\Parameter $parameter */
249 170
            $types[$parameter->getName()] = $parameter->getType();
250
        }
251
252
        // Return previous parser result if the query and the filter collection are both clean
253 747
        if ($this->_state === self::STATE_CLEAN && $this->_parsedTypes === $types && $this->_em->isFiltersStateClean()) {
254 39
            return $this->_parserResult;
255
        }
256
257 747
        $this->_state = self::STATE_CLEAN;
258 747
        $this->_parsedTypes = $types;
259
260
        // Check query cache.
261 747
        if ( ! ($this->_useQueryCache && ($queryCache = $this->getQueryCacheDriver()))) {
262 172
            $parser = new Parser($this);
263
264 172
            $this->_parserResult = $parser->parse();
265
266 168
            return $this->_parserResult;
267
        }
268
269 575
        $hash   = $this->_getQueryCacheId();
270 575
        $cached = $this->_expireQueryCache ? false : $queryCache->fetch($hash);
0 ignored issues
show
Bug introduced by
The variable $queryCache does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
271
272 575
        if ($cached instanceof ParserResult) {
273
            // Cache hit.
274 118
            $this->_parserResult = $cached;
275
276 118
            return $this->_parserResult;
277
        }
278
279
        // Cache miss.
280 525
        $parser = new Parser($this);
281
282 525
        $this->_parserResult = $parser->parse();
283
284 506
        $queryCache->save($hash, $this->_parserResult, $this->_queryCacheTTL);
285
286 506
        return $this->_parserResult;
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     */
292 446
    protected function _doExecute()
293
    {
294 446
        $executor = $this->_parse()->getSqlExecutor();
295
296 437
        if ($this->_queryCacheProfile) {
297 8
            $executor->setQueryCacheProfile($this->_queryCacheProfile);
298
        } else {
299 431
            $executor->removeQueryCacheProfile();
300
        }
301
302 437
        if ($this->_resultSetMapping === null) {
303 395
            $this->_resultSetMapping = $this->_parserResult->getResultSetMapping();
304
        }
305
306
        // Prepare parameters
307 437
        $paramMappings = $this->_parserResult->getParameterMappings();
308 437
        $paramCount = count($this->parameters);
309 437
        $mappingCount = count($paramMappings);
310
311 437
        if ($paramCount > $mappingCount) {
312 1
            throw QueryException::tooManyParameters($mappingCount, $paramCount);
313
        }
314
315 436
        if ($paramCount < $mappingCount) {
316 1
            throw QueryException::tooFewParameters($mappingCount, $paramCount);
317
        }
318
319
        // evict all cache for the entity region
320 435
        if ($this->hasCache && isset($this->_hints[self::HINT_CACHE_EVICT]) && $this->_hints[self::HINT_CACHE_EVICT]) {
321 2
            $this->evictEntityCacheRegion();
322
        }
323
324 435
        list($sqlParams, $types) = $this->processParameterMappings($paramMappings);
325
326 434
        $this->evictResultSetCache(
327 434
            $executor,
328 434
            $sqlParams,
329 434
            $types,
330 434
            $this->_em->getConnection()->getParams()
331
        );
332
333 434
        return $executor->execute($this->_em->getConnection(), $sqlParams, $types);
334
    }
335
336 434
    private function evictResultSetCache(
337
        AbstractSqlExecutor $executor,
338
        array $sqlParams,
339
        array $types,
340
        array $connectionParams
341
    ) {
342 434
        if (null === $this->_queryCacheProfile || ! $this->getExpireResultCache()) {
343 434
            return;
344
        }
345
346 2
        $cacheDriver = $this->_queryCacheProfile->getResultCacheDriver();
347 2
        $statements  = (array) $executor->getSqlStatements(); // Type casted since it can either be a string or an array
348
349 2
        foreach ($statements as $statement) {
350 2
            $cacheKeys = $this->_queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types, $connectionParams);
351
352 2
            $cacheDriver->delete(reset($cacheKeys));
0 ignored issues
show
Security Bug introduced by
It seems like reset($cacheKeys) targeting reset() can also be of type false; however, Doctrine\Common\Cache\Cache::delete() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
353
        }
354 2
    }
355
356
    /**
357
     * Evict entity cache region
358
     */
359 2
    private function evictEntityCacheRegion()
360
    {
361 2
        $AST = $this->getAST();
362
363 2
        if ($AST instanceof \Doctrine\ORM\Query\AST\SelectStatement) {
364
            throw new QueryException('The hint "HINT_CACHE_EVICT" is not valid for select statements.');
365
        }
366
367 2
        $className = ($AST instanceof \Doctrine\ORM\Query\AST\DeleteStatement)
368 1
            ? $AST->deleteClause->abstractSchemaName
369 2
            : $AST->updateClause->abstractSchemaName;
370
371 2
        $this->_em->getCache()->evictEntityRegion($className);
372 2
    }
373
374
    /**
375
     * Processes query parameter mappings.
376
     *
377
     * @param array $paramMappings
378
     *
379
     * @return array
380
     *
381
     * @throws Query\QueryException
382
     */
383 435
    private function processParameterMappings($paramMappings)
384
    {
385 435
        $sqlParams = [];
386 435
        $types     = [];
387
388 435
        foreach ($this->parameters as $parameter) {
389 158
            $key    = $parameter->getName();
390 158
            $value  = $parameter->getValue();
391 158
            $rsm    = $this->getResultSetMapping();
392
393 158
            if ( ! isset($paramMappings[$key])) {
394 1
                throw QueryException::unknownParameter($key);
395
            }
396
397 157
            if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
398 2
                $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
399
            }
400
401 157
            $value = $this->processParameterValue($value);
402 157
            $type  = ($parameter->getValue() === $value)
403 146
                ? $parameter->getType()
404 157
                : ParameterTypeInferer::inferType($value);
405
406 157
            foreach ($paramMappings[$key] as $position) {
407 157
                $types[$position] = $type;
408
            }
409
410 157
            $sqlPositions = $paramMappings[$key];
411
412
            // optimized multi value sql positions away for now,
413
            // they are not allowed in DQL anyways.
414 157
            $value = [$value];
415 157
            $countValue = count($value);
416
417 157
            for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) {
418 157
                $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
419
            }
420
        }
421
422 434
        if (count($sqlParams) != count($types)) {
423
            throw QueryException::parameterTypeMismatch();
424
        }
425
426 434
        if ($sqlParams) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sqlParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
427 157
            ksort($sqlParams);
428 157
            $sqlParams = array_values($sqlParams);
429
430 157
            ksort($types);
431 157
            $types = array_values($types);
432
        }
433
434 434
        return [$sqlParams, $types];
435
    }
436
437
    /**
438
     * Defines a cache driver to be used for caching queries.
439
     *
440
     * @param \Doctrine\Common\Cache\Cache|null $queryCache Cache driver.
441
     *
442
     * @return Query This query instance.
443
     */
444 6
    public function setQueryCacheDriver($queryCache)
445
    {
446 6
        $this->_queryCache = $queryCache;
447
448 6
        return $this;
449
    }
450
451
    /**
452
     * Defines whether the query should make use of a query cache, if available.
453
     *
454
     * @param boolean $bool
455
     *
456
     * @return Query This query instance.
457
     */
458 175
    public function useQueryCache($bool)
459
    {
460 175
        $this->_useQueryCache = $bool;
461
462 175
        return $this;
463
    }
464
465
    /**
466
     * Returns the cache driver used for query caching.
467
     *
468
     * @return \Doctrine\Common\Cache\Cache|null The cache driver used for query caching or NULL, if
469
     *                                           this Query does not use query caching.
470
     */
471 575
    public function getQueryCacheDriver()
472
    {
473 575
        if ($this->_queryCache) {
474 9
            return $this->_queryCache;
475
        }
476
477 566
        return $this->_em->getConfiguration()->getQueryCacheImpl();
478
    }
479
480
    /**
481
     * Defines how long the query cache will be active before expire.
482
     *
483
     * @param integer $timeToLive How long the cache entry is valid.
484
     *
485
     * @return Query This query instance.
486
     */
487 1
    public function setQueryCacheLifetime($timeToLive)
488
    {
489 1
        if ($timeToLive !== null) {
490 1
            $timeToLive = (int) $timeToLive;
491
        }
492
493 1
        $this->_queryCacheTTL = $timeToLive;
494
495 1
        return $this;
496
    }
497
498
    /**
499
     * Retrieves the lifetime of resultset cache.
500
     *
501
     * @return int
502
     */
503
    public function getQueryCacheLifetime()
504
    {
505
        return $this->_queryCacheTTL;
506
    }
507
508
    /**
509
     * Defines if the query cache is active or not.
510
     *
511
     * @param boolean $expire Whether or not to force query cache expiration.
512
     *
513
     * @return Query This query instance.
514
     */
515 7
    public function expireQueryCache($expire = true)
516
    {
517 7
        $this->_expireQueryCache = $expire;
518
519 7
        return $this;
520
    }
521
522
    /**
523
     * Retrieves if the query cache is active or not.
524
     *
525
     * @return bool
526
     */
527
    public function getExpireQueryCache()
528
    {
529
        return $this->_expireQueryCache;
530
    }
531
532
    /**
533
     * @override
534
     */
535 211
    public function free()
536
    {
537 211
        parent::free();
538
539 211
        $this->_dql = null;
540 211
        $this->_state = self::STATE_CLEAN;
541 211
    }
542
543
    /**
544
     * Sets a DQL query string.
545
     *
546
     * @param string $dqlQuery DQL Query.
547
     *
548
     * @return \Doctrine\ORM\AbstractQuery
549
     */
550 930
    public function setDQL($dqlQuery)
551
    {
552 930
        if ($dqlQuery !== null) {
553 930
            $this->_dql = $dqlQuery;
554 930
            $this->_state = self::STATE_DIRTY;
555
        }
556
557 930
        return $this;
558
    }
559
560
    /**
561
     * Returns the DQL query that is represented by this query object.
562
     *
563
     * @return string DQL query.
564
     */
565 882
    public function getDQL()
566
    {
567 882
        return $this->_dql;
568
    }
569
570
    /**
571
     * Returns the state of this query object
572
     * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
573
     * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
574
     *
575
     * @see AbstractQuery::STATE_CLEAN
576
     * @see AbstractQuery::STATE_DIRTY
577
     *
578
     * @return integer The query state.
579
     */
580
    public function getState()
581
    {
582
        return $this->_state;
583
    }
584
585
    /**
586
     * Method to check if an arbitrary piece of DQL exists
587
     *
588
     * @param string $dql Arbitrary piece of DQL to check for.
589
     *
590
     * @return boolean
591
     */
592
    public function contains($dql)
593
    {
594
        return stripos($this->getDQL(), $dql) !== false;
595
    }
596
597
    /**
598
     * Sets the position of the first result to retrieve (the "offset").
599
     *
600
     * @param integer $firstResult The first result to return.
601
     *
602
     * @return Query This query object.
603
     */
604 216
    public function setFirstResult($firstResult)
605
    {
606 216
        $this->_firstResult = $firstResult;
607 216
        $this->_state       = self::STATE_DIRTY;
608
609 216
        return $this;
610
    }
611
612
    /**
613
     * Gets the position of the first result the query object was set to retrieve (the "offset").
614
     * Returns NULL if {@link setFirstResult} was not applied to this query.
615
     *
616
     * @return integer The position of the first result.
617
     */
618 635
    public function getFirstResult()
619
    {
620 635
        return $this->_firstResult;
621
    }
622
623
    /**
624
     * Sets the maximum number of results to retrieve (the "limit").
625
     *
626
     * @param integer $maxResults
627
     *
628
     * @return Query This query object.
629
     */
630 225
    public function setMaxResults($maxResults)
631
    {
632 225
        $this->_maxResults = $maxResults;
633 225
        $this->_state      = self::STATE_DIRTY;
634
635 225
        return $this;
636
    }
637
638
    /**
639
     * Gets the maximum number of results the query object was set to retrieve (the "limit").
640
     * Returns NULL if {@link setMaxResults} was not applied to this query.
641
     *
642
     * @return integer Maximum number of results.
643
     */
644 635
    public function getMaxResults()
645
    {
646 635
        return $this->_maxResults;
647
    }
648
649
    /**
650
     * Executes the query and returns an IterableResult that can be used to incrementally
651
     * iterated over the result.
652
     *
653
     * @param ArrayCollection|array|null $parameters    The query parameters.
654
     * @param integer                    $hydrationMode The hydration mode to use.
655
     *
656
     * @return \Doctrine\ORM\Internal\Hydration\IterableResult
657
     */
658 10
    public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT)
659
    {
660 10
        $this->setHint(self::HINT_INTERNAL_ITERATION, true);
661
662 10
        return parent::iterate($parameters, $hydrationMode);
663
    }
664
665
    /**
666
     * {@inheritdoc}
667
     */
668 460
    public function setHint($name, $value)
669
    {
670 460
        $this->_state = self::STATE_DIRTY;
671
672 460
        return parent::setHint($name, $value);
673
    }
674
675
    /**
676
     * {@inheritdoc}
677
     */
678 344
    public function setHydrationMode($hydrationMode)
679
    {
680 344
        $this->_state = self::STATE_DIRTY;
681
682 344
        return parent::setHydrationMode($hydrationMode);
683
    }
684
685
    /**
686
     * Set the lock mode for this Query.
687
     *
688
     * @see \Doctrine\DBAL\LockMode
689
     *
690
     * @param int $lockMode
691
     *
692
     * @return Query
693
     *
694
     * @throws TransactionRequiredException
695
     */
696
    public function setLockMode($lockMode)
697
    {
698
        if (in_array($lockMode, [LockMode::NONE, LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE], true)) {
699
            if ( ! $this->_em->getConnection()->isTransactionActive()) {
700
                throw TransactionRequiredException::transactionRequired();
701
            }
702
        }
703
704
        $this->setHint(self::HINT_LOCK_MODE, $lockMode);
705
706
        return $this;
707
    }
708
709
    /**
710
     * Get the current lock mode for this query.
711
     *
712
     * @return int|null The current lock mode of this query or NULL if no specific lock mode is set.
713
     */
714
    public function getLockMode()
715
    {
716
        $lockMode = $this->getHint(self::HINT_LOCK_MODE);
717
718
        if (false === $lockMode) {
719
            return null;
720
        }
721
722
        return $lockMode;
723
    }
724
725
    /**
726
     * Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
727
     *
728
     * @return string
729
     */
730 575
    protected function _getQueryCacheId()
731
    {
732 575
        ksort($this->_hints);
733
734 575
        $platform = $this->getEntityManager()
735 575
            ->getConnection()
736 575
            ->getDatabasePlatform()
737 575
            ->getName();
738
739 575
        return md5(
740 575
            $this->getDQL() . serialize($this->_hints) .
741 575
            '&platform=' . $platform .
742 575
            ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') .
743 575
            '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults .
744 575
            '&hydrationMode=' . $this->_hydrationMode . '&types=' . serialize($this->_parsedTypes) . 'DOCTRINE_QUERY_CACHE_SALT'
745
        );
746
    }
747
748
     /**
749
     * {@inheritdoc}
750
     */
751 28
    protected function getHash()
752
    {
753 28
        return sha1(parent::getHash(). '-'. $this->_firstResult . '-' . $this->_maxResults);
754
    }
755
756
    /**
757
     * Cleanup Query resource when clone is called.
758
     *
759
     * @return void
760
     */
761 136
    public function __clone()
762
    {
763 136
        parent::__clone();
764
765 136
        $this->_state = self::STATE_DIRTY;
766 136
    }
767
}
768