Completed
Push — master ( 2c1ebc...7bb02d )
by Marco
11s
created

Query::useQueryCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
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 421
    protected function getResultSetMapping()
227
    {
228
        // parse query or load from cache
229 421
        if ($this->_resultSetMapping === null) {
230 37
            $this->_resultSetMapping = $this->_parse()->getResultSetMapping();
231
        }
232
233 418
        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 739
    private function _parse()
244
    {
245 739
        $types = [];
246
247 739
        foreach ($this->parameters as $parameter) {
248
            /** @var Query\Parameter $parameter */
249 164
            $types[$parameter->getName()] = $parameter->getType();
250
        }
251
252
        // Return previous parser result if the query and the filter collection are both clean
253 739
        if ($this->_state === self::STATE_CLEAN && $this->_parsedTypes === $types && $this->_em->isFiltersStateClean()) {
254 39
            return $this->_parserResult;
255
        }
256
257 739
        $this->_state = self::STATE_CLEAN;
258 739
        $this->_parsedTypes = $types;
259
260
        // Check query cache.
261 739
        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 567
        $hash   = $this->_getQueryCacheId();
270 567
        $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 567
        if ($cached instanceof ParserResult) {
273
            // Cache hit.
274 116
            $this->_parserResult = $cached;
275
276 116
            return $this->_parserResult;
277
        }
278
279
        // Cache miss.
280 519
        $parser = new Parser($this);
281
282 519
        $this->_parserResult = $parser->parse();
283
284 500
        $queryCache->save($hash, $this->_parserResult, $this->_queryCacheTTL);
285
286 500
        return $this->_parserResult;
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     */
292 438
    protected function _doExecute()
293
    {
294 438
        $executor = $this->_parse()->getSqlExecutor();
295
296 429
        if ($this->_queryCacheProfile) {
297 8
            $executor->setQueryCacheProfile($this->_queryCacheProfile);
298
        } else {
299 423
            $executor->removeQueryCacheProfile();
300
        }
301
302 429
        if ($this->_resultSetMapping === null) {
303 388
            $this->_resultSetMapping = $this->_parserResult->getResultSetMapping();
304
        }
305
306
        // Prepare parameters
307 429
        $paramMappings = $this->_parserResult->getParameterMappings();
308 429
        $paramCount = count($this->parameters);
309 429
        $mappingCount = count($paramMappings);
310
311 429
        if ($paramCount > $mappingCount) {
312 1
            throw QueryException::tooManyParameters($mappingCount, $paramCount);
313
        }
314
315 428
        if ($paramCount < $mappingCount) {
316 1
            throw QueryException::tooFewParameters($mappingCount, $paramCount);
317
        }
318
319
        // evict all cache for the entity region
320 427
        if ($this->hasCache && isset($this->_hints[self::HINT_CACHE_EVICT]) && $this->_hints[self::HINT_CACHE_EVICT]) {
321 2
            $this->evictEntityCacheRegion();
322
        }
323
324 427
        list($sqlParams, $types) = $this->processParameterMappings($paramMappings);
325
326 426
        $this->evictResultSetCache($executor, $sqlParams, $types);
327
328 426
        return $executor->execute($this->_em->getConnection(), $sqlParams, $types);
329
    }
330
331 426
    private function evictResultSetCache(AbstractSqlExecutor $executor, array $sqlParams, array $types)
332
    {
333 426
        if (null === $this->_queryCacheProfile || ! $this->getExpireResultCache()) {
334 426
            return;
335
        }
336
337 2
        $cacheDriver = $this->_queryCacheProfile->getResultCacheDriver();
338 2
        $statements  = (array) $executor->getSqlStatements(); // Type casted since it can either be a string or an array
339
340 2
        foreach ($statements as $statement) {
341 2
            $cacheKeys = $this->_queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types);
342
343 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...
344
        }
345 2
    }
346
347
    /**
348
     * Evict entity cache region
349
     */
350 2
    private function evictEntityCacheRegion()
351
    {
352 2
        $AST = $this->getAST();
353
354 2
        if ($AST instanceof \Doctrine\ORM\Query\AST\SelectStatement) {
355
            throw new QueryException('The hint "HINT_CACHE_EVICT" is not valid for select statements.');
356
        }
357
358 2
        $className = ($AST instanceof \Doctrine\ORM\Query\AST\DeleteStatement)
359 1
            ? $AST->deleteClause->abstractSchemaName
360 2
            : $AST->updateClause->abstractSchemaName;
361
362 2
        $this->_em->getCache()->evictEntityRegion($className);
363 2
    }
364
365
    /**
366
     * Processes query parameter mappings.
367
     *
368
     * @param array $paramMappings
369
     *
370
     * @return array
371
     *
372
     * @throws Query\QueryException
373
     */
374 427
    private function processParameterMappings($paramMappings)
375
    {
376 427
        $sqlParams = [];
377 427
        $types     = [];
378
379 427
        foreach ($this->parameters as $parameter) {
380 152
            $key    = $parameter->getName();
381 152
            $value  = $parameter->getValue();
382 152
            $rsm    = $this->getResultSetMapping();
383
384 152
            if ( ! isset($paramMappings[$key])) {
385 1
                throw QueryException::unknownParameter($key);
386
            }
387
388 151
            if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
389 2
                $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
390
            }
391
392 151
            $value = $this->processParameterValue($value);
393 151
            $type  = ($parameter->getValue() === $value)
394 141
                ? $parameter->getType()
395 151
                : ParameterTypeInferer::inferType($value);
396
397 151
            foreach ($paramMappings[$key] as $position) {
398 151
                $types[$position] = $type;
399
            }
400
401 151
            $sqlPositions = $paramMappings[$key];
402
403
            // optimized multi value sql positions away for now,
404
            // they are not allowed in DQL anyways.
405 151
            $value = [$value];
406 151
            $countValue = count($value);
407
408 151
            for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) {
409 151
                $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
410
            }
411
        }
412
413 426
        if (count($sqlParams) != count($types)) {
414
            throw QueryException::parameterTypeMismatch();
415
        }
416
417 426
        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...
418 151
            ksort($sqlParams);
419 151
            $sqlParams = array_values($sqlParams);
420
421 151
            ksort($types);
422 151
            $types = array_values($types);
423
        }
424
425 426
        return [$sqlParams, $types];
426
    }
427
428
    /**
429
     * Defines a cache driver to be used for caching queries.
430
     *
431
     * @param \Doctrine\Common\Cache\Cache|null $queryCache Cache driver.
432
     *
433
     * @return Query This query instance.
434
     */
435 6
    public function setQueryCacheDriver($queryCache)
436
    {
437 6
        $this->_queryCache = $queryCache;
438
439 6
        return $this;
440
    }
441
442
    /**
443
     * Defines whether the query should make use of a query cache, if available.
444
     *
445
     * @param boolean $bool
446
     *
447
     * @return Query This query instance.
448
     */
449 175
    public function useQueryCache($bool)
450
    {
451 175
        $this->_useQueryCache = $bool;
452
453 175
        return $this;
454
    }
455
456
    /**
457
     * Returns the cache driver used for query caching.
458
     *
459
     * @return \Doctrine\Common\Cache\Cache|null The cache driver used for query caching or NULL, if
460
     *                                           this Query does not use query caching.
461
     */
462 567
    public function getQueryCacheDriver()
463
    {
464 567
        if ($this->_queryCache) {
465 9
            return $this->_queryCache;
466
        }
467
468 558
        return $this->_em->getConfiguration()->getQueryCacheImpl();
469
    }
470
471
    /**
472
     * Defines how long the query cache will be active before expire.
473
     *
474
     * @param integer $timeToLive How long the cache entry is valid.
475
     *
476
     * @return Query This query instance.
477
     */
478 1
    public function setQueryCacheLifetime($timeToLive)
479
    {
480 1
        if ($timeToLive !== null) {
481 1
            $timeToLive = (int) $timeToLive;
482
        }
483
484 1
        $this->_queryCacheTTL = $timeToLive;
485
486 1
        return $this;
487
    }
488
489
    /**
490
     * Retrieves the lifetime of resultset cache.
491
     *
492
     * @return int
493
     */
494
    public function getQueryCacheLifetime()
495
    {
496
        return $this->_queryCacheTTL;
497
    }
498
499
    /**
500
     * Defines if the query cache is active or not.
501
     *
502
     * @param boolean $expire Whether or not to force query cache expiration.
503
     *
504
     * @return Query This query instance.
505
     */
506 7
    public function expireQueryCache($expire = true)
507
    {
508 7
        $this->_expireQueryCache = $expire;
509
510 7
        return $this;
511
    }
512
513
    /**
514
     * Retrieves if the query cache is active or not.
515
     *
516
     * @return bool
517
     */
518
    public function getExpireQueryCache()
519
    {
520
        return $this->_expireQueryCache;
521
    }
522
523
    /**
524
     * @override
525
     */
526 211
    public function free()
527
    {
528 211
        parent::free();
529
530 211
        $this->_dql = null;
531 211
        $this->_state = self::STATE_CLEAN;
532 211
    }
533
534
    /**
535
     * Sets a DQL query string.
536
     *
537
     * @param string $dqlQuery DQL Query.
538
     *
539
     * @return \Doctrine\ORM\AbstractQuery
540
     */
541 922
    public function setDQL($dqlQuery)
542
    {
543 922
        if ($dqlQuery !== null) {
544 922
            $this->_dql = $dqlQuery;
545 922
            $this->_state = self::STATE_DIRTY;
546
        }
547
548 922
        return $this;
549
    }
550
551
    /**
552
     * Returns the DQL query that is represented by this query object.
553
     *
554
     * @return string DQL query.
555
     */
556 874
    public function getDQL()
557
    {
558 874
        return $this->_dql;
559
    }
560
561
    /**
562
     * Returns the state of this query object
563
     * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
564
     * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
565
     *
566
     * @see AbstractQuery::STATE_CLEAN
567
     * @see AbstractQuery::STATE_DIRTY
568
     *
569
     * @return integer The query state.
570
     */
571
    public function getState()
572
    {
573
        return $this->_state;
574
    }
575
576
    /**
577
     * Method to check if an arbitrary piece of DQL exists
578
     *
579
     * @param string $dql Arbitrary piece of DQL to check for.
580
     *
581
     * @return boolean
582
     */
583
    public function contains($dql)
584
    {
585
        return stripos($this->getDQL(), $dql) !== false;
586
    }
587
588
    /**
589
     * Sets the position of the first result to retrieve (the "offset").
590
     *
591
     * @param integer $firstResult The first result to return.
592
     *
593
     * @return Query This query object.
594
     */
595 214
    public function setFirstResult($firstResult)
596
    {
597 214
        $this->_firstResult = $firstResult;
598 214
        $this->_state       = self::STATE_DIRTY;
599
600 214
        return $this;
601
    }
602
603
    /**
604
     * Gets the position of the first result the query object was set to retrieve (the "offset").
605
     * Returns NULL if {@link setFirstResult} was not applied to this query.
606
     *
607
     * @return integer The position of the first result.
608
     */
609 631
    public function getFirstResult()
610
    {
611 631
        return $this->_firstResult;
612
    }
613
614
    /**
615
     * Sets the maximum number of results to retrieve (the "limit").
616
     *
617
     * @param integer $maxResults
618
     *
619
     * @return Query This query object.
620
     */
621 223
    public function setMaxResults($maxResults)
622
    {
623 223
        $this->_maxResults = $maxResults;
624 223
        $this->_state      = self::STATE_DIRTY;
625
626 223
        return $this;
627
    }
628
629
    /**
630
     * Gets the maximum number of results the query object was set to retrieve (the "limit").
631
     * Returns NULL if {@link setMaxResults} was not applied to this query.
632
     *
633
     * @return integer Maximum number of results.
634
     */
635 631
    public function getMaxResults()
636
    {
637 631
        return $this->_maxResults;
638
    }
639
640
    /**
641
     * Executes the query and returns an IterableResult that can be used to incrementally
642
     * iterated over the result.
643
     *
644
     * @param ArrayCollection|array|null $parameters    The query parameters.
645
     * @param integer                    $hydrationMode The hydration mode to use.
646
     *
647
     * @return \Doctrine\ORM\Internal\Hydration\IterableResult
648
     */
649 9
    public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT)
650
    {
651 9
        $this->setHint(self::HINT_INTERNAL_ITERATION, true);
652
653 9
        return parent::iterate($parameters, $hydrationMode);
654
    }
655
656
    /**
657
     * {@inheritdoc}
658
     */
659 459
    public function setHint($name, $value)
660
    {
661 459
        $this->_state = self::STATE_DIRTY;
662
663 459
        return parent::setHint($name, $value);
664
    }
665
666
    /**
667
     * {@inheritdoc}
668
     */
669 339
    public function setHydrationMode($hydrationMode)
670
    {
671 339
        $this->_state = self::STATE_DIRTY;
672
673 339
        return parent::setHydrationMode($hydrationMode);
674
    }
675
676
    /**
677
     * Set the lock mode for this Query.
678
     *
679
     * @see \Doctrine\DBAL\LockMode
680
     *
681
     * @param int $lockMode
682
     *
683
     * @return Query
684
     *
685
     * @throws TransactionRequiredException
686
     */
687
    public function setLockMode($lockMode)
688
    {
689
        if (in_array($lockMode, [LockMode::NONE, LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE], true)) {
690
            if ( ! $this->_em->getConnection()->isTransactionActive()) {
691
                throw TransactionRequiredException::transactionRequired();
692
            }
693
        }
694
695
        $this->setHint(self::HINT_LOCK_MODE, $lockMode);
696
697
        return $this;
698
    }
699
700
    /**
701
     * Get the current lock mode for this query.
702
     *
703
     * @return int|null The current lock mode of this query or NULL if no specific lock mode is set.
704
     */
705
    public function getLockMode()
706
    {
707
        $lockMode = $this->getHint(self::HINT_LOCK_MODE);
708
709
        if (false === $lockMode) {
710
            return null;
711
        }
712
713
        return $lockMode;
714
    }
715
716
    /**
717
     * Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
718
     *
719
     * @return string
720
     */
721 567
    protected function _getQueryCacheId()
722
    {
723 567
        ksort($this->_hints);
724
725 567
        $platform = $this->getEntityManager()
726 567
            ->getConnection()
727 567
            ->getDatabasePlatform()
728 567
            ->getName();
729
730 567
        return md5(
731 567
            $this->getDql() . serialize($this->_hints) .
732 567
            '&platform=' . $platform .
733 567
            ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') .
734 567
            '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults .
735 567
            '&hydrationMode=' . $this->_hydrationMode . '&types=' . serialize($this->_parsedTypes) . 'DOCTRINE_QUERY_CACHE_SALT'
736
        );
737
    }
738
739
     /**
740
     * {@inheritdoc}
741
     */
742 28
    protected function getHash()
743
    {
744 28
        return sha1(parent::getHash(). '-'. $this->_firstResult . '-' . $this->_maxResults);
745
    }
746
747
    /**
748
     * Cleanup Query resource when clone is called.
749
     *
750
     * @return void
751
     */
752 136
    public function __clone()
753
    {
754 136
        parent::__clone();
755
756 136
        $this->_state = self::STATE_DIRTY;
757 136
    }
758
}
759