AbstractQuery.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. namespace Doctrine\ORM;
  20. use Doctrine\Common\Util\ClassUtils;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Doctrine\DBAL\Types\Type;
  23. use Doctrine\DBAL\Cache\QueryCacheProfile;
  24. use Doctrine\ORM\Query\QueryException;
  25. use Doctrine\ORM\Mapping;
  26. /**
  27. * Base contract for ORM queries. Base class for Query and NativeQuery.
  28. *
  29. * @link www.doctrine-project.org
  30. * @since 2.0
  31. * @author Benjamin Eberlei <kontakt@beberlei.de>
  32. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  33. * @author Jonathan Wage <jonwage@gmail.com>
  34. * @author Roman Borschel <roman@code-factory.org>
  35. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  36. */
  37. abstract class AbstractQuery
  38. {
  39. /* Hydration mode constants */
  40. /**
  41. * Hydrates an object graph. This is the default behavior.
  42. */
  43. const HYDRATE_OBJECT = 1;
  44. /**
  45. * Hydrates an array graph.
  46. */
  47. const HYDRATE_ARRAY = 2;
  48. /**
  49. * Hydrates a flat, rectangular result set with scalar values.
  50. */
  51. const HYDRATE_SCALAR = 3;
  52. /**
  53. * Hydrates a single scalar value.
  54. */
  55. const HYDRATE_SINGLE_SCALAR = 4;
  56. /**
  57. * Very simple object hydrator (optimized for performance).
  58. */
  59. const HYDRATE_SIMPLEOBJECT = 5;
  60. /**
  61. * @var \Doctrine\Common\Collections\ArrayCollection The parameter map of this query.
  62. */
  63. protected $parameters;
  64. /**
  65. * @var ResultSetMapping The user-specified ResultSetMapping to use.
  66. */
  67. protected $_resultSetMapping;
  68. /**
  69. * @var \Doctrine\ORM\EntityManager The entity manager used by this query object.
  70. */
  71. protected $_em;
  72. /**
  73. * @var array The map of query hints.
  74. */
  75. protected $_hints = array();
  76. /**
  77. * @var integer The hydration mode.
  78. */
  79. protected $_hydrationMode = self::HYDRATE_OBJECT;
  80. /**
  81. * @param \Doctrine\DBAL\Cache\QueryCacheProfile
  82. */
  83. protected $_queryCacheProfile;
  84. /**
  85. * @var boolean Boolean value that indicates whether or not expire the result cache.
  86. */
  87. protected $_expireResultCache = false;
  88. /**
  89. * @param \Doctrine\DBAL\Cache\QueryCacheProfile
  90. */
  91. protected $_hydrationCacheProfile;
  92. /**
  93. * Initializes a new instance of a class derived from <tt>AbstractQuery</tt>.
  94. *
  95. * @param \Doctrine\ORM\EntityManager $entityManager
  96. */
  97. public function __construct(EntityManager $em)
  98. {
  99. $this->_em = $em;
  100. $this->parameters = new ArrayCollection();
  101. }
  102. /**
  103. * Gets the SQL query that corresponds to this query object.
  104. * The returned SQL syntax depends on the connection driver that is used
  105. * by this query object at the time of this method call.
  106. *
  107. * @return string SQL query
  108. */
  109. abstract public function getSQL();
  110. /**
  111. * Retrieves the associated EntityManager of this Query instance.
  112. *
  113. * @return \Doctrine\ORM\EntityManager
  114. */
  115. public function getEntityManager()
  116. {
  117. return $this->_em;
  118. }
  119. /**
  120. * Frees the resources used by the query object.
  121. *
  122. * Resets Parameters, Parameter Types and Query Hints.
  123. *
  124. * @return void
  125. */
  126. public function free()
  127. {
  128. $this->parameters = new ArrayCollection();
  129. $this->_hints = array();
  130. }
  131. /**
  132. * Get all defined parameters.
  133. *
  134. * @return \Doctrine\Common\Collections\ArrayCollection The defined query parameters.
  135. */
  136. public function getParameters()
  137. {
  138. return $this->parameters;
  139. }
  140. /**
  141. * Gets a query parameter.
  142. *
  143. * @param mixed $key The key (index or name) of the bound parameter.
  144. *
  145. * @return mixed The value of the bound parameter.
  146. */
  147. public function getParameter($key)
  148. {
  149. $filteredParameters = $this->parameters->filter(
  150. function ($parameter) use ($key)
  151. {
  152. // Must not be identical because of string to integer conversion
  153. return ($key == $parameter->getName());
  154. }
  155. );
  156. return count($filteredParameters) ? $filteredParameters->first() : null;
  157. }
  158. /**
  159. * Sets a collection of query parameters.
  160. *
  161. * @param \Doctrine\Common\Collections\ArrayCollection|array $parameters
  162. *
  163. * @return \Doctrine\ORM\AbstractQuery This query instance.
  164. */
  165. public function setParameters($parameters)
  166. {
  167. // BC compatibility with 2.3-
  168. if (is_array($parameters)) {
  169. $parameterCollection = new ArrayCollection();
  170. foreach ($parameters as $key => $value) {
  171. $parameter = new Query\Parameter($key, $value);
  172. $parameterCollection->add($parameter);
  173. }
  174. $parameters = $parameterCollection;
  175. }
  176. $this->parameters = $parameters;
  177. return $this;
  178. }
  179. /**
  180. * Sets a query parameter.
  181. *
  182. * @param string|integer $key The parameter position or name.
  183. * @param mixed $value The parameter value.
  184. * @param string $type The parameter type. If specified, the given value will be run through
  185. * the type conversion of this type. This is usually not needed for
  186. * strings and numeric types.
  187. *
  188. * @return \Doctrine\ORM\AbstractQuery This query instance.
  189. */
  190. public function setParameter($key, $value, $type = null)
  191. {
  192. $filteredParameters = $this->parameters->filter(
  193. function ($parameter) use ($key)
  194. {
  195. // Must not be identical because of string to integer conversion
  196. return ($key == $parameter->getName());
  197. }
  198. );
  199. if (count($filteredParameters)) {
  200. $parameter = $filteredParameters->first();
  201. $parameter->setValue($value, $type);
  202. return $this;
  203. }
  204. $parameter = new Query\Parameter($key, $value, $type);
  205. $this->parameters->add($parameter);
  206. return $this;
  207. }
  208. /**
  209. * Process an individual parameter value
  210. *
  211. * @param mixed $value
  212. * @return array
  213. */
  214. public function processParameterValue($value)
  215. {
  216. switch (true) {
  217. case is_array($value):
  218. foreach ($value as $key => $paramValue) {
  219. $paramValue = $this->processParameterValue($paramValue);
  220. $value[$key] = is_array($paramValue) ? $paramValue[key($paramValue)] : $paramValue;
  221. }
  222. return $value;
  223. case is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value)):
  224. return $this->convertObjectParameterToScalarValue($value);
  225. case ($value instanceof Mapping\ClassMetadata):
  226. return $value->name;
  227. default:
  228. return $value;
  229. }
  230. }
  231. private function convertObjectParameterToScalarValue($value)
  232. {
  233. $class = $this->_em->getClassMetadata(get_class($value));
  234. if ($class->isIdentifierComposite) {
  235. throw new \InvalidArgumentException(
  236. "Binding an entity with a composite primary key to a query is not supported. " .
  237. "You should split the parameter into the explicit fields and bind them seperately."
  238. );
  239. }
  240. $values = ($this->_em->getUnitOfWork()->getEntityState($value) === UnitOfWork::STATE_MANAGED)
  241. ? $this->_em->getUnitOfWork()->getEntityIdentifier($value)
  242. : $class->getIdentifierValues($value);
  243. $value = $values[$class->getSingleIdentifierFieldName()];
  244. if (null === $value) {
  245. throw new \InvalidArgumentException(
  246. "Binding entities to query parameters only allowed for entities that have an identifier."
  247. );
  248. }
  249. return $value;
  250. }
  251. /**
  252. * Sets the ResultSetMapping that should be used for hydration.
  253. *
  254. * @param ResultSetMapping $rsm
  255. * @return \Doctrine\ORM\AbstractQuery
  256. */
  257. public function setResultSetMapping(Query\ResultSetMapping $rsm)
  258. {
  259. $this->_resultSetMapping = $rsm;
  260. return $this;
  261. }
  262. /**
  263. * Set a cache profile for hydration caching.
  264. *
  265. * If no result cache driver is set in the QueryCacheProfile, the default
  266. * result cache driver is used from the configuration.
  267. *
  268. * Important: Hydration caching does NOT register entities in the
  269. * UnitOfWork when retrieved from the cache. Never use result cached
  270. * entities for requests that also flush the EntityManager. If you want
  271. * some form of caching with UnitOfWork registration you should use
  272. * {@see AbstractQuery::setResultCacheProfile()}.
  273. *
  274. * @example
  275. * $lifetime = 100;
  276. * $resultKey = "abc";
  277. * $query->setHydrationCacheProfile(new QueryCacheProfile());
  278. * $query->setHydrationCacheProfile(new QueryCacheProfile($lifetime, $resultKey));
  279. *
  280. * @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile
  281. * @return \Doctrine\ORM\AbstractQuery
  282. */
  283. public function setHydrationCacheProfile(QueryCacheProfile $profile = null)
  284. {
  285. if ( ! $profile->getResultCacheDriver()) {
  286. $resultCacheDriver = $this->_em->getConfiguration()->getHydrationCacheImpl();
  287. $profile = $profile->setResultCacheDriver($resultCacheDriver);
  288. }
  289. $this->_hydrationCacheProfile = $profile;
  290. return $this;
  291. }
  292. /**
  293. * @return \Doctrine\DBAL\Cache\QueryCacheProfile
  294. */
  295. public function getHydrationCacheProfile()
  296. {
  297. return $this->_hydrationCacheProfile;
  298. }
  299. /**
  300. * Set a cache profile for the result cache.
  301. *
  302. * If no result cache driver is set in the QueryCacheProfile, the default
  303. * result cache driver is used from the configuration.
  304. *
  305. * @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile
  306. * @return \Doctrine\ORM\AbstractQuery
  307. */
  308. public function setResultCacheProfile(QueryCacheProfile $profile = null)
  309. {
  310. if ( ! $profile->getResultCacheDriver()) {
  311. $resultCacheDriver = $this->_em->getConfiguration()->getResultCacheImpl();
  312. $profile = $profile->setResultCacheDriver($resultCacheDriver);
  313. }
  314. $this->_queryCacheProfile = $profile;
  315. return $this;
  316. }
  317. /**
  318. * Defines a cache driver to be used for caching result sets and implictly enables caching.
  319. *
  320. * @param \Doctrine\Common\Cache\Cache $driver Cache driver
  321. * @return \Doctrine\ORM\AbstractQuery
  322. */
  323. public function setResultCacheDriver($resultCacheDriver = null)
  324. {
  325. if ($resultCacheDriver !== null && ! ($resultCacheDriver instanceof \Doctrine\Common\Cache\Cache)) {
  326. throw ORMException::invalidResultCacheDriver();
  327. }
  328. $this->_queryCacheProfile = $this->_queryCacheProfile
  329. ? $this->_queryCacheProfile->setResultCacheDriver($resultCacheDriver)
  330. : new QueryCacheProfile(0, null, $resultCacheDriver);
  331. return $this;
  332. }
  333. /**
  334. * Returns the cache driver used for caching result sets.
  335. *
  336. * @deprecated
  337. * @return \Doctrine\Common\Cache\Cache Cache driver
  338. */
  339. public function getResultCacheDriver()
  340. {
  341. if ($this->_queryCacheProfile && $this->_queryCacheProfile->getResultCacheDriver()) {
  342. return $this->_queryCacheProfile->getResultCacheDriver();
  343. }
  344. return $this->_em->getConfiguration()->getResultCacheImpl();
  345. }
  346. /**
  347. * Set whether or not to cache the results of this query and if so, for
  348. * how long and which ID to use for the cache entry.
  349. *
  350. * @param boolean $bool
  351. * @param integer $lifetime
  352. * @param string $resultCacheId
  353. * @return \Doctrine\ORM\AbstractQuery This query instance.
  354. */
  355. public function useResultCache($bool, $lifetime = null, $resultCacheId = null)
  356. {
  357. if ($bool) {
  358. $this->setResultCacheLifetime($lifetime);
  359. $this->setResultCacheId($resultCacheId);
  360. return $this;
  361. }
  362. $this->_queryCacheProfile = null;
  363. return $this;
  364. }
  365. /**
  366. * Defines how long the result cache will be active before expire.
  367. *
  368. * @param integer $lifetime How long the cache entry is valid.
  369. * @return \Doctrine\ORM\AbstractQuery This query instance.
  370. */
  371. public function setResultCacheLifetime($lifetime)
  372. {
  373. $lifetime = ($lifetime !== null) ? (int) $lifetime : 0;
  374. $this->_queryCacheProfile = $this->_queryCacheProfile
  375. ? $this->_queryCacheProfile->setLifetime($lifetime)
  376. : new QueryCacheProfile($lifetime, null, $this->_em->getConfiguration()->getResultCacheImpl());
  377. return $this;
  378. }
  379. /**
  380. * Retrieves the lifetime of resultset cache.
  381. *
  382. * @deprecated
  383. * @return integer
  384. */
  385. public function getResultCacheLifetime()
  386. {
  387. return $this->_queryCacheProfile ? $this->_queryCacheProfile->getLifetime() : 0;
  388. }
  389. /**
  390. * Defines if the result cache is active or not.
  391. *
  392. * @param boolean $expire Whether or not to force resultset cache expiration.
  393. * @return \Doctrine\ORM\AbstractQuery This query instance.
  394. */
  395. public function expireResultCache($expire = true)
  396. {
  397. $this->_expireResultCache = $expire;
  398. return $this;
  399. }
  400. /**
  401. * Retrieves if the resultset cache is active or not.
  402. *
  403. * @return boolean
  404. */
  405. public function getExpireResultCache()
  406. {
  407. return $this->_expireResultCache;
  408. }
  409. /**
  410. * @return QueryCacheProfile
  411. */
  412. public function getQueryCacheProfile()
  413. {
  414. return $this->_queryCacheProfile;
  415. }
  416. /**
  417. * Change the default fetch mode of an association for this query.
  418. *
  419. * $fetchMode can be one of ClassMetadata::FETCH_EAGER or ClassMetadata::FETCH_LAZY
  420. *
  421. * @param string $class
  422. * @param string $assocName
  423. * @param int $fetchMode
  424. * @return AbstractQuery
  425. */
  426. public function setFetchMode($class, $assocName, $fetchMode)
  427. {
  428. if ($fetchMode !== Mapping\ClassMetadata::FETCH_EAGER) {
  429. $fetchMode = Mapping\ClassMetadata::FETCH_LAZY;
  430. }
  431. $this->_hints['fetchMode'][$class][$assocName] = $fetchMode;
  432. return $this;
  433. }
  434. /**
  435. * Defines the processing mode to be used during hydration / result set transformation.
  436. *
  437. * @param integer $hydrationMode Doctrine processing mode to be used during hydration process.
  438. * One of the Query::HYDRATE_* constants.
  439. * @return \Doctrine\ORM\AbstractQuery This query instance.
  440. */
  441. public function setHydrationMode($hydrationMode)
  442. {
  443. $this->_hydrationMode = $hydrationMode;
  444. return $this;
  445. }
  446. /**
  447. * Gets the hydration mode currently used by the query.
  448. *
  449. * @return integer
  450. */
  451. public function getHydrationMode()
  452. {
  453. return $this->_hydrationMode;
  454. }
  455. /**
  456. * Gets the list of results for the query.
  457. *
  458. * Alias for execute(null, $hydrationMode = HYDRATE_OBJECT).
  459. *
  460. * @return array
  461. */
  462. public function getResult($hydrationMode = self::HYDRATE_OBJECT)
  463. {
  464. return $this->execute(null, $hydrationMode);
  465. }
  466. /**
  467. * Gets the array of results for the query.
  468. *
  469. * Alias for execute(null, HYDRATE_ARRAY).
  470. *
  471. * @return array
  472. */
  473. public function getArrayResult()
  474. {
  475. return $this->execute(null, self::HYDRATE_ARRAY);
  476. }
  477. /**
  478. * Gets the scalar results for the query.
  479. *
  480. * Alias for execute(null, HYDRATE_SCALAR).
  481. *
  482. * @return array
  483. */
  484. public function getScalarResult()
  485. {
  486. return $this->execute(null, self::HYDRATE_SCALAR);
  487. }
  488. /**
  489. * Get exactly one result or null.
  490. *
  491. * @throws NonUniqueResultException
  492. * @param int $hydrationMode
  493. * @return mixed
  494. */
  495. public function getOneOrNullResult($hydrationMode = null)
  496. {
  497. $result = $this->execute(null, $hydrationMode);
  498. if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
  499. return null;
  500. }
  501. if ( ! is_array($result)) {
  502. return $result;
  503. }
  504. if (count($result) > 1) {
  505. throw new NonUniqueResultException;
  506. }
  507. return array_shift($result);
  508. }
  509. /**
  510. * Gets the single result of the query.
  511. *
  512. * Enforces the presence as well as the uniqueness of the result.
  513. *
  514. * If the result is not unique, a NonUniqueResultException is thrown.
  515. * If there is no result, a NoResultException is thrown.
  516. *
  517. * @param integer $hydrationMode
  518. * @return mixed
  519. * @throws NonUniqueResultException If the query result is not unique.
  520. * @throws NoResultException If the query returned no result.
  521. */
  522. public function getSingleResult($hydrationMode = null)
  523. {
  524. $result = $this->execute(null, $hydrationMode);
  525. if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
  526. throw new NoResultException;
  527. }
  528. if ( ! is_array($result)) {
  529. return $result;
  530. }
  531. if (count($result) > 1) {
  532. throw new NonUniqueResultException;
  533. }
  534. return array_shift($result);
  535. }
  536. /**
  537. * Gets the single scalar result of the query.
  538. *
  539. * Alias for getSingleResult(HYDRATE_SINGLE_SCALAR).
  540. *
  541. * @return mixed
  542. * @throws QueryException If the query result is not unique.
  543. */
  544. public function getSingleScalarResult()
  545. {
  546. return $this->getSingleResult(self::HYDRATE_SINGLE_SCALAR);
  547. }
  548. /**
  549. * Sets a query hint. If the hint name is not recognized, it is silently ignored.
  550. *
  551. * @param string $name The name of the hint.
  552. * @param mixed $value The value of the hint.
  553. * @return \Doctrine\ORM\AbstractQuery
  554. */
  555. public function setHint($name, $value)
  556. {
  557. $this->_hints[$name] = $value;
  558. return $this;
  559. }
  560. /**
  561. * Gets the value of a query hint. If the hint name is not recognized, FALSE is returned.
  562. *
  563. * @param string $name The name of the hint.
  564. * @return mixed The value of the hint or FALSE, if the hint name is not recognized.
  565. */
  566. public function getHint($name)
  567. {
  568. return isset($this->_hints[$name]) ? $this->_hints[$name] : false;
  569. }
  570. /**
  571. * Return the key value map of query hints that are currently set.
  572. *
  573. * @return array
  574. */
  575. public function getHints()
  576. {
  577. return $this->_hints;
  578. }
  579. /**
  580. * Executes the query and returns an IterableResult that can be used to incrementally
  581. * iterate over the result.
  582. *
  583. * @param \Doctrine\Common\Collections\ArrayCollection|array $parameters The query parameters.
  584. * @param integer $hydrationMode The hydration mode to use.
  585. * @return \Doctrine\ORM\Internal\Hydration\IterableResult
  586. */
  587. public function iterate($parameters = null, $hydrationMode = null)
  588. {
  589. if ($hydrationMode !== null) {
  590. $this->setHydrationMode($hydrationMode);
  591. }
  592. if ( ! empty($parameters)) {
  593. $this->setParameters($parameters);
  594. }
  595. $stmt = $this->_doExecute();
  596. return $this->_em->newHydrator($this->_hydrationMode)->iterate(
  597. $stmt, $this->_resultSetMapping, $this->_hints
  598. );
  599. }
  600. /**
  601. * Executes the query.
  602. *
  603. * @param \Doctrine\Common\Collections\ArrayCollection|array $parameters Query parameters.
  604. * @param integer $hydrationMode Processing mode to be used during the hydration process.
  605. * @return mixed
  606. */
  607. public function execute($parameters = null, $hydrationMode = null)
  608. {
  609. if ($hydrationMode !== null) {
  610. $this->setHydrationMode($hydrationMode);
  611. }
  612. if ( ! empty($parameters)) {
  613. $this->setParameters($parameters);
  614. }
  615. $setCacheEntry = function() {};
  616. if ($this->_hydrationCacheProfile !== null) {
  617. list($cacheKey, $realCacheKey) = $this->getHydrationCacheId();
  618. $queryCacheProfile = $this->getHydrationCacheProfile();
  619. $cache = $queryCacheProfile->getResultCacheDriver();
  620. $result = $cache->fetch($cacheKey);
  621. if (isset($result[$realCacheKey])) {
  622. return $result[$realCacheKey];
  623. }
  624. if ( ! $result) {
  625. $result = array();
  626. }
  627. $setCacheEntry = function($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile) {
  628. $result[$realCacheKey] = $data;
  629. $cache->save($cacheKey, $result, $queryCacheProfile->getLifetime());
  630. };
  631. }
  632. $stmt = $this->_doExecute();
  633. if (is_numeric($stmt)) {
  634. $setCacheEntry($stmt);
  635. return $stmt;
  636. }
  637. $data = $this->_em->getHydrator($this->_hydrationMode)->hydrateAll(
  638. $stmt, $this->_resultSetMapping, $this->_hints
  639. );
  640. $setCacheEntry($data);
  641. return $data;
  642. }
  643. /**
  644. * Get the result cache id to use to store the result set cache entry.
  645. * Will return the configured id if it exists otherwise a hash will be
  646. * automatically generated for you.
  647. *
  648. * @return array ($key, $hash)
  649. */
  650. protected function getHydrationCacheId()
  651. {
  652. $parameters = array();
  653. foreach ($this->getParameters() as $parameter) {
  654. $parameters[$parameter->getName()] = $this->processParameterValue($parameter->getValue());
  655. }
  656. $sql = $this->getSQL();
  657. $queryCacheProfile = $this->getHydrationCacheProfile();
  658. $hints = $this->getHints();
  659. $hints['hydrationMode'] = $this->getHydrationMode();
  660. ksort($hints);
  661. return $queryCacheProfile->generateCacheKeys($sql, $parameters, $hints);
  662. }
  663. /**
  664. * Set the result cache id to use to store the result set cache entry.
  665. * If this is not explicitly set by the developer then a hash is automatically
  666. * generated for you.
  667. *
  668. * @param string $id
  669. * @return \Doctrine\ORM\AbstractQuery This query instance.
  670. */
  671. public function setResultCacheId($id)
  672. {
  673. $this->_queryCacheProfile = $this->_queryCacheProfile
  674. ? $this->_queryCacheProfile->setCacheKey($id)
  675. : new QueryCacheProfile(0, $id, $this->_em->getConfiguration()->getResultCacheImpl());
  676. return $this;
  677. }
  678. /**
  679. * Get the result cache id to use to store the result set cache entry if set.
  680. *
  681. * @deprecated
  682. * @return string
  683. */
  684. public function getResultCacheId()
  685. {
  686. return $this->_queryCacheProfile ? $this->_queryCacheProfile->getCacheKey() : null;
  687. }
  688. /**
  689. * Executes the query and returns a the resulting Statement object.
  690. *
  691. * @return \Doctrine\DBAL\Driver\Statement The executed database statement that holds the results.
  692. */
  693. abstract protected function _doExecute();
  694. /**
  695. * Cleanup Query resource when clone is called.
  696. *
  697. * @return void
  698. */
  699. public function __clone()
  700. {
  701. $this->parameters = new ArrayCollection();
  702. $this->_hints = array();
  703. }
  704. }