Failed Conditions
Pull Request — master (#7885)
by Šimon
09:39
created

Query::getIterable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM;
6
7
use Doctrine\Common\Cache\Cache;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Doctrine\ORM\Cache. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Doctrine\Common\Collections\ArrayCollection;
9
use Doctrine\DBAL\LockMode;
10
use Doctrine\ORM\Internal\Hydration\IterableNewResult;
11
use Doctrine\ORM\Internal\Hydration\IterableResult;
12
use Doctrine\ORM\Mapping\ClassMetadata;
13
use Doctrine\ORM\Query\AST\DeleteStatement;
14
use Doctrine\ORM\Query\AST\SelectStatement;
15
use Doctrine\ORM\Query\AST\UpdateStatement;
16
use Doctrine\ORM\Query\Exec\AbstractSqlExecutor;
17
use Doctrine\ORM\Query\Parameter;
18
use Doctrine\ORM\Query\ParameterTypeInferer;
19
use Doctrine\ORM\Query\Parser;
20
use Doctrine\ORM\Query\ParserResult;
21
use Doctrine\ORM\Query\QueryException;
22
use Doctrine\ORM\Utility\HierarchyDiscriminatorResolver;
23
use function array_keys;
24
use function array_values;
25
use function assert;
26
use function count;
27
use function in_array;
28
use function ksort;
29
use function md5;
30
use function reset;
31
use function serialize;
32
use function sha1;
33
use function stripos;
34
35
/**
36
 * A Query object represents a DQL query.
37
 */
38
final class Query extends AbstractQuery
39
{
40
    /**
41
     * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.
42
     */
43
    public const STATE_CLEAN = 1;
44
45
    /**
46
     * A query object is in state DIRTY when it has DQL parts that have not yet been
47
     * parsed/processed. This is automatically defined as DIRTY when addDqlQueryPart
48
     * is called.
49
     */
50
    public const STATE_DIRTY = 2;
51
52
    /* Query HINTS */
53
54
    /**
55
     * The refresh hint turns any query into a refresh query with the result that
56
     * any local changes in entities are overridden with the fetched values.
57
     */
58
    public const HINT_REFRESH = 'doctrine.refresh';
59
60
    public const HINT_CACHE_ENABLED = 'doctrine.cache.enabled';
61
62
    public const HINT_CACHE_EVICT = 'doctrine.cache.evict';
63
64
    /**
65
     * Internal hint: is set to the proxy entity that is currently triggered for loading
66
     */
67
    public const HINT_REFRESH_ENTITY = 'doctrine.refresh.entity';
68
69
    /**
70
     * The forcePartialLoad query hint forces a particular query to return
71
     * partial objects.
72
     *
73
     * @todo Rename: HINT_OPTIMIZE
74
     */
75
    public const HINT_FORCE_PARTIAL_LOAD = 'doctrine.forcePartialLoad';
76
77
    /**
78
     * The includeMetaColumns query hint causes meta columns like foreign keys and
79
     * discriminator columns to be selected and returned as part of the query result.
80
     *
81
     * This hint does only apply to non-object queries.
82
     */
83
    public const HINT_INCLUDE_META_COLUMNS = 'doctrine.includeMetaColumns';
84
85
    /**
86
     * An array of class names that implement \Doctrine\ORM\Query\TreeWalker and
87
     * are iterated and executed after the DQL has been parsed into an AST.
88
     */
89
    public const HINT_CUSTOM_TREE_WALKERS = 'doctrine.customTreeWalkers';
90
91
    /**
92
     * A string with a class name that implements \Doctrine\ORM\Query\TreeWalker
93
     * and is used for generating the target SQL from any DQL AST tree.
94
     */
95
    public const HINT_CUSTOM_OUTPUT_WALKER = 'doctrine.customOutputWalker';
96
97
    //const HINT_READ_ONLY = 'doctrine.readOnly';
98
99
    public const HINT_INTERNAL_ITERATION = 'doctrine.internal.iteration';
100
101
    public const HINT_LOCK_MODE = 'doctrine.lockMode';
102
103
    /**
104
     * The current state of this query.
105
     *
106
     * @var int
107
     */
108
    private $state = self::STATE_CLEAN;
109
110
    /**
111
     * A snapshot of the parameter types the query was parsed with.
112
     *
113
     * @var mixed[]
114
     */
115
    private $parsedTypes = [];
116
117
    /**
118
     * Cached DQL query.
119
     *
120
     * @var string
121
     */
122
    private $dql;
123
124
    /**
125
     * The parser result that holds DQL => SQL information.
126
     *
127
     * @var ParserResult
128
     */
129
    private $parserResult;
130
131
    /**
132
     * The first result to return (the "offset").
133
     *
134
     * @var int
135
     */
136
    private $firstResult;
137
138
    /**
139
     * The maximum number of results to return (the "limit").
140
     *
141
     * @var int|null
142
     */
143
    private $maxResults;
144
145
    /**
146
     * The cache driver used for caching queries.
147
     *
148
     * @var Cache|null
149
     */
150
    private $queryCache;
151
152
    /**
153
     * Whether or not expire the query cache.
154
     *
155
     * @var bool
156
     */
157
    private $expireQueryCache = false;
158
159
    /**
160
     * The query cache lifetime.
161
     *
162
     * @var int
163
     */
164
    private $queryCacheTTL;
165
166
    /**
167
     * Whether to use a query cache, if available. Defaults to TRUE.
168
     *
169
     * @var bool
170
     */
171
    private $useQueryCache = true;
172
173
    /**
174
     * Gets the SQL query/queries that correspond to this DQL query.
175
     *
176
     * @return mixed The built sql query or an array of all sql queries.
177
     *
178
     * @override
179
     */
180 342
    public function getSQL()
181
    {
182 342
        return $this->parse()->getSqlExecutor()->getSqlStatements();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->parse()->g...r()->getSqlStatements() returns the type string[] which is incompatible with the return type mandated by Doctrine\ORM\AbstractQuery::getSQL() of string.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
183
    }
184
185
    /**
186
     * Returns the corresponding AST for this DQL query.
187
     *
188
     * @return SelectStatement|UpdateStatement|DeleteStatement
189
     */
190 2
    public function getAST()
191
    {
192 2
        $parser = new Parser($this);
193
194 2
        return $parser->getAST();
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200 450
    protected function getResultSetMapping()
201
    {
202
        // parse query or load from cache
203 450
        if ($this->resultSetMapping === null) {
204 38
            $this->resultSetMapping = $this->parse()->getResultSetMapping();
205
        }
206
207 447
        return $this->resultSetMapping;
208
    }
209
210
    /**
211
     * Parses the DQL query, if necessary, and stores the parser result.
212
     *
213
     * Note: Populates $this->parserResult as a side-effect.
214
     *
215
     * @return ParserResult
216
     */
217 775
    private function parse()
218
    {
219 775
        $types = [];
220
221 775
        foreach ($this->parameters as $parameter) {
222
            /** @var Query\Parameter $parameter */
223 178
            $types[$parameter->getName()] = $parameter->getType();
224
        }
225
226
        // Return previous parser result if the query and the filter collection are both clean
227 775
        if ($this->state === self::STATE_CLEAN && $this->parsedTypes === $types && $this->em->isFiltersStateClean()) {
228 39
            return $this->parserResult;
229
        }
230
231 775
        $this->state       = self::STATE_CLEAN;
232 775
        $this->parsedTypes = $types;
233
234
        // Check query cache.
235 775
        $queryCache = $this->getQueryCacheDriver();
236 775
        if (! ($this->useQueryCache && $queryCache)) {
237 181
            $parser = new Parser($this);
238
239 181
            $this->parserResult = $parser->parse();
240
241 177
            return $this->parserResult;
242
        }
243
244 594
        $hash   = $this->getQueryCacheId();
245 594
        $cached = $this->expireQueryCache ? false : $queryCache->fetch($hash);
246
247 594
        if ($cached instanceof ParserResult) {
248
            // Cache hit.
249 131
            $this->parserResult = $cached;
250
251 131
            return $this->parserResult;
252
        }
253
254
        // Cache miss.
255 542
        $parser = new Parser($this);
256
257 542
        $this->parserResult = $parser->parse();
258
259 526
        $queryCache->save($hash, $this->parserResult, $this->queryCacheTTL);
260
261 526
        return $this->parserResult;
262
    }
263
264
    /**
265
     * {@inheritdoc}
266
     */
267 465
    protected function doExecute()
268
    {
269 465
        $executor = $this->parse()->getSqlExecutor();
270
271 460
        if ($this->queryCacheProfile) {
272 8
            $executor->setQueryCacheProfile($this->queryCacheProfile);
273
        } else {
274 454
            $executor->removeQueryCacheProfile();
275
        }
276
277 460
        if ($this->resultSetMapping === null) {
278 418
            $this->resultSetMapping = $this->parserResult->getResultSetMapping();
279
        }
280
281
        // Prepare parameters
282 460
        $paramMappings = $this->parserResult->getParameterMappings();
283 460
        $paramCount    = count($this->parameters);
284 460
        $mappingCount  = count($paramMappings);
285
286 460
        if ($paramCount > $mappingCount) {
287 2
            throw QueryException::tooManyParameters($mappingCount, $paramCount);
288
        }
289
290 459
        if ($paramCount < $mappingCount) {
291 1
            throw QueryException::tooFewParameters($mappingCount, $paramCount);
292
        }
293
294
        // evict all cache for the entity region
295 458
        if ($this->hasCache && isset($this->hints[self::HINT_CACHE_EVICT]) && $this->hints[self::HINT_CACHE_EVICT]) {
296 2
            $this->evictEntityCacheRegion();
297
        }
298
299 458
        [$sqlParams, $types] = $this->processParameterMappings($paramMappings);
300
301 457
        $this->evictResultSetCache(
302 457
            $executor,
303 457
            $sqlParams,
304 457
            $types,
305 457
            $this->em->getConnection()->getParams()
306
        );
307
308 457
        return $executor->execute($this->em->getConnection(), $sqlParams, $types);
309
    }
310
311
    /**
312
     * @param mixed[] $sqlParams
313
     * @param mixed[] $types
314
     * @param mixed[] $connectionParams
315
     */
316 457
    private function evictResultSetCache(
317
        AbstractSqlExecutor $executor,
318
        array $sqlParams,
319
        array $types,
320
        array $connectionParams
321
    ) {
322 457
        if ($this->queryCacheProfile === null || ! $this->getExpireResultCache()) {
323 457
            return;
324
        }
325
326 2
        $cacheDriver = $this->queryCacheProfile->getResultCacheDriver();
327 2
        $statements  = (array) $executor->getSqlStatements(); // Type casted since it can either be a string or an array
328
329 2
        foreach ($statements as $statement) {
330 2
            $cacheKeys = $this->queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types, $connectionParams);
331
332 2
            $cacheDriver->delete(reset($cacheKeys));
333
        }
334 2
    }
335
336
    /**
337
     * Evict entity cache region
338
     */
339 2
    private function evictEntityCacheRegion()
340
    {
341 2
        $AST = $this->getAST();
342
343 2
        if ($AST instanceof SelectStatement) {
344
            throw new QueryException('The hint "HINT_CACHE_EVICT" is not valid for select statements.');
345
        }
346
347 2
        $className = $AST instanceof DeleteStatement
348 1
            ? $AST->deleteClause->abstractSchemaName
349 2
            : $AST->updateClause->abstractSchemaName;
350
351 2
        $this->em->getCache()->evictEntityRegion($className);
352 2
    }
353
354
    /**
355
     * Processes query parameter mappings.
356
     *
357
     * @param mixed[] $paramMappings
358
     *
359
     * @return mixed[][]
360
     *
361
     * @throws Query\QueryException
362
     */
363 458
    private function processParameterMappings($paramMappings)
364
    {
365 458
        $sqlParams = [];
366 458
        $types     = [];
367
368 458
        foreach ($this->parameters as $parameter) {
369 165
            $key = $parameter->getName();
370
371 165
            if (! isset($paramMappings[$key])) {
372 1
                throw QueryException::unknownParameter($key);
373
            }
374
375 164
            [$value, $type] = $this->resolveParameterValue($parameter);
376
377 164
            foreach ($paramMappings[$key] as $position) {
378 164
                $types[$position] = $type;
379
            }
380
381 164
            $sqlPositions      = $paramMappings[$key];
382 164
            $sqlPositionsCount = count($sqlPositions);
383
384
            // optimized multi value sql positions away for now,
385
            // they are not allowed in DQL anyways.
386 164
            $value      = [$value];
387 164
            $countValue = count($value);
388
389 164
            for ($i = 0, $l = $sqlPositionsCount; $i < $l; $i++) {
390 164
                $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
391
            }
392
        }
393
394 457
        if (count($sqlParams) !== count($types)) {
395
            throw QueryException::parameterTypeMismatch();
396
        }
397
398 457
        if ($sqlParams) {
399 164
            ksort($sqlParams);
400 164
            $sqlParams = array_values($sqlParams);
401
402 164
            ksort($types);
403 164
            $types = array_values($types);
404
        }
405
406 457
        return [$sqlParams, $types];
407
    }
408
409
    /** @return mixed[] tuple of (value, type) */
410 164
    private function resolveParameterValue(Parameter $parameter) : array
411
    {
412 164
        if ($parameter->typeWasSpecified()) {
413 5
            return [$parameter->getValue(), $parameter->getType()];
414
        }
415
416 160
        $key           = $parameter->getName();
417 160
        $originalValue = $parameter->getValue();
418 160
        $value         = $originalValue;
419 160
        $rsm           = $this->getResultSetMapping();
420
421 160
        assert($rsm !== null);
422
423 160
        if ($value instanceof ClassMetadata && isset($rsm->metadataParameterMapping[$key])) {
424
            $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
0 ignored issues
show
Bug introduced by
The method getMetadataValue() does not exist on Doctrine\ORM\Mapping\ClassMetadata. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

424
            /** @scrutinizer ignore-call */ 
425
            $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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