ObjectHydrator.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM\Internal\Hydration;
  20. use PDO,
  21. Doctrine\ORM\Mapping\ClassMetadata,
  22. Doctrine\ORM\PersistentCollection,
  23. Doctrine\ORM\Query,
  24. Doctrine\Common\Collections\ArrayCollection,
  25. Doctrine\Common\Collections\Collection,
  26. Doctrine\ORM\Proxy\Proxy;
  27. /**
  28. * The ObjectHydrator constructs an object graph out of an SQL result set.
  29. *
  30. * @author Roman Borschel <roman@code-factory.org>
  31. * @since 2.0
  32. * @internal Highly performance-sensitive code.
  33. */
  34. class ObjectHydrator extends AbstractHydrator
  35. {
  36. /* Local ClassMetadata cache to avoid going to the EntityManager all the time.
  37. * This local cache is maintained between hydration runs and not cleared.
  38. */
  39. private $_ce = array();
  40. /* The following parts are reinitialized on every hydration run. */
  41. private $_identifierMap;
  42. private $_resultPointers;
  43. private $_idTemplate;
  44. private $_resultCounter;
  45. private $_rootAliases = array();
  46. private $_initializedCollections = array();
  47. private $_existingCollections = array();
  48. //private $_createdEntities;
  49. /** @override */
  50. protected function _prepare()
  51. {
  52. $this->_identifierMap =
  53. $this->_resultPointers =
  54. $this->_idTemplate = array();
  55. $this->_resultCounter = 0;
  56. if (!isset($this->_hints['deferEagerLoad'])) {
  57. $this->_hints['deferEagerLoad'] = true;
  58. }
  59. foreach ($this->_rsm->aliasMap as $dqlAlias => $className) {
  60. $this->_identifierMap[$dqlAlias] = array();
  61. $this->_idTemplate[$dqlAlias] = '';
  62. $class = $this->_em->getClassMetadata($className);
  63. if ( ! isset($this->_ce[$className])) {
  64. $this->_ce[$className] = $class;
  65. }
  66. // Remember which associations are "fetch joined", so that we know where to inject
  67. // collection stubs or proxies and where not.
  68. if (isset($this->_rsm->relationMap[$dqlAlias])) {
  69. if ( ! isset($this->_rsm->aliasMap[$this->_rsm->parentAliasMap[$dqlAlias]])) {
  70. throw HydrationException::parentObjectOfRelationNotFound($dqlAlias, $this->_rsm->parentAliasMap[$dqlAlias]);
  71. }
  72. $sourceClassName = $this->_rsm->aliasMap[$this->_rsm->parentAliasMap[$dqlAlias]];
  73. $sourceClass = $this->_getClassMetadata($sourceClassName);
  74. $assoc = $sourceClass->associationMappings[$this->_rsm->relationMap[$dqlAlias]];
  75. $this->_hints['fetched'][$this->_rsm->parentAliasMap[$dqlAlias]][$assoc['fieldName']] = true;
  76. if ($assoc['type'] != ClassMetadata::MANY_TO_MANY) {
  77. // Mark any non-collection opposite sides as fetched, too.
  78. if ($assoc['mappedBy']) {
  79. $this->_hints['fetched'][$dqlAlias][$assoc['mappedBy']] = true;
  80. } else {
  81. if ($assoc['inversedBy']) {
  82. $inverseAssoc = $class->associationMappings[$assoc['inversedBy']];
  83. if ($inverseAssoc['type'] & ClassMetadata::TO_ONE) {
  84. $this->_hints['fetched'][$dqlAlias][$inverseAssoc['fieldName']] = true;
  85. }
  86. }
  87. }
  88. }
  89. }
  90. }
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. protected function _cleanup()
  96. {
  97. $eagerLoad = (isset($this->_hints['deferEagerLoad'])) && $this->_hints['deferEagerLoad'] == true;
  98. parent::_cleanup();
  99. $this->_identifierMap =
  100. $this->_initializedCollections =
  101. $this->_existingCollections =
  102. $this->_resultPointers = array();
  103. if ($eagerLoad) {
  104. $this->_em->getUnitOfWork()->triggerEagerLoads();
  105. }
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. protected function _hydrateAll()
  111. {
  112. $result = array();
  113. $cache = array();
  114. while ($row = $this->_stmt->fetch(PDO::FETCH_ASSOC)) {
  115. $this->_hydrateRow($row, $cache, $result);
  116. }
  117. // Take snapshots from all newly initialized collections
  118. foreach ($this->_initializedCollections as $coll) {
  119. $coll->takeSnapshot();
  120. }
  121. return $result;
  122. }
  123. /**
  124. * Initializes a related collection.
  125. *
  126. * @param object $entity The entity to which the collection belongs.
  127. * @param string $name The name of the field on the entity that holds the collection.
  128. */
  129. private function _initRelatedCollection($entity, $class, $fieldName, $parentDqlAlias)
  130. {
  131. $oid = spl_object_hash($entity);
  132. $relation = $class->associationMappings[$fieldName];
  133. $value = $class->reflFields[$fieldName]->getValue($entity);
  134. if ($value === null) {
  135. $value = new ArrayCollection;
  136. }
  137. if ( ! $value instanceof PersistentCollection) {
  138. $value = new PersistentCollection(
  139. $this->_em,
  140. $this->_ce[$relation['targetEntity']],
  141. $value
  142. );
  143. $value->setOwner($entity, $relation);
  144. $class->reflFields[$fieldName]->setValue($entity, $value);
  145. $this->_uow->setOriginalEntityProperty($oid, $fieldName, $value);
  146. $this->_initializedCollections[$oid . $fieldName] = $value;
  147. } else if (isset($this->_hints[Query::HINT_REFRESH]) ||
  148. isset($this->_hints['fetched'][$parentDqlAlias][$fieldName]) &&
  149. ! $value->isInitialized()) {
  150. // Is already PersistentCollection, but either REFRESH or FETCH-JOIN and UNINITIALIZED!
  151. $value->setDirty(false);
  152. $value->setInitialized(true);
  153. $value->unwrap()->clear();
  154. $this->_initializedCollections[$oid . $fieldName] = $value;
  155. } else {
  156. // Is already PersistentCollection, and DON'T REFRESH or FETCH-JOIN!
  157. $this->_existingCollections[$oid . $fieldName] = $value;
  158. }
  159. return $value;
  160. }
  161. /**
  162. * Gets an entity instance.
  163. *
  164. * @param $data The instance data.
  165. * @param $dqlAlias The DQL alias of the entity's class.
  166. * @return object The entity.
  167. */
  168. private function _getEntity(array $data, $dqlAlias)
  169. {
  170. $className = $this->_rsm->aliasMap[$dqlAlias];
  171. if (isset($this->_rsm->discriminatorColumns[$dqlAlias])) {
  172. $discrColumn = $this->_rsm->metaMappings[$this->_rsm->discriminatorColumns[$dqlAlias]];
  173. $className = $this->_ce[$className]->discriminatorMap[$data[$discrColumn]];
  174. unset($data[$discrColumn]);
  175. }
  176. if (isset($this->_hints[Query::HINT_REFRESH_ENTITY]) && isset($this->_rootAliases[$dqlAlias])) {
  177. $class = $this->_ce[$className];
  178. $this->registerManaged($class, $this->_hints[Query::HINT_REFRESH_ENTITY], $data);
  179. }
  180. $this->_hints['fetchAlias'] = $dqlAlias;
  181. return $this->_uow->createEntity($className, $data, $this->_hints);
  182. }
  183. private function _getEntityFromIdentityMap($className, array $data)
  184. {
  185. // TODO: Abstract this code and UnitOfWork::createEntity() equivalent?
  186. $class = $this->_ce[$className];
  187. /* @var $class ClassMetadata */
  188. if ($class->isIdentifierComposite) {
  189. $idHash = '';
  190. foreach ($class->identifier as $fieldName) {
  191. if (isset($class->associationMappings[$fieldName])) {
  192. $idHash .= $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] . ' ';
  193. } else {
  194. $idHash .= $data[$fieldName] . ' ';
  195. }
  196. }
  197. return $this->_uow->tryGetByIdHash(rtrim($idHash), $class->rootEntityName);
  198. } else if (isset($class->associationMappings[$class->identifier[0]])) {
  199. return $this->_uow->tryGetByIdHash($data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']], $class->rootEntityName);
  200. } else {
  201. return $this->_uow->tryGetByIdHash($data[$class->identifier[0]], $class->rootEntityName);
  202. }
  203. }
  204. /**
  205. * Gets a ClassMetadata instance from the local cache.
  206. * If the instance is not yet in the local cache, it is loaded into the
  207. * local cache.
  208. *
  209. * @param string $className The name of the class.
  210. * @return ClassMetadata
  211. */
  212. private function _getClassMetadata($className)
  213. {
  214. if ( ! isset($this->_ce[$className])) {
  215. $this->_ce[$className] = $this->_em->getClassMetadata($className);
  216. }
  217. return $this->_ce[$className];
  218. }
  219. /**
  220. * Hydrates a single row in an SQL result set.
  221. *
  222. * @internal
  223. * First, the data of the row is split into chunks where each chunk contains data
  224. * that belongs to a particular component/class. Afterwards, all these chunks
  225. * are processed, one after the other. For each chunk of class data only one of the
  226. * following code paths is executed:
  227. *
  228. * Path A: The data chunk belongs to a joined/associated object and the association
  229. * is collection-valued.
  230. * Path B: The data chunk belongs to a joined/associated object and the association
  231. * is single-valued.
  232. * Path C: The data chunk belongs to a root result element/object that appears in the topmost
  233. * level of the hydrated result. A typical example are the objects of the type
  234. * specified by the FROM clause in a DQL query.
  235. *
  236. * @param array $data The data of the row to process.
  237. * @param array $cache The cache to use.
  238. * @param array $result The result array to fill.
  239. */
  240. protected function _hydrateRow(array $data, array &$cache, array &$result)
  241. {
  242. // Initialize
  243. $id = $this->_idTemplate; // initialize the id-memory
  244. $nonemptyComponents = array();
  245. // Split the row data into chunks of class data.
  246. $rowData = $this->_gatherRowData($data, $cache, $id, $nonemptyComponents);
  247. // Extract scalar values. They're appended at the end.
  248. if (isset($rowData['scalars'])) {
  249. $scalars = $rowData['scalars'];
  250. unset($rowData['scalars']);
  251. if (empty($rowData)) {
  252. ++$this->_resultCounter;
  253. }
  254. }
  255. // Hydrate the data chunks
  256. foreach ($rowData as $dqlAlias => $data) {
  257. $entityName = $this->_rsm->aliasMap[$dqlAlias];
  258. if (isset($this->_rsm->parentAliasMap[$dqlAlias])) {
  259. // It's a joined result
  260. $parentAlias = $this->_rsm->parentAliasMap[$dqlAlias];
  261. // we need the $path to save into the identifier map which entities were already
  262. // seen for this parent-child relationship
  263. $path = $parentAlias . '.' . $dqlAlias;
  264. // We have a RIGHT JOIN result here. Doctrine cannot hydrate RIGHT JOIN Object-Graphs
  265. if (!isset($nonemptyComponents[$parentAlias])) {
  266. // TODO: Add special case code where we hydrate the right join objects into identity map at least
  267. continue;
  268. }
  269. // Get a reference to the parent object to which the joined element belongs.
  270. if ($this->_rsm->isMixed && isset($this->_rootAliases[$parentAlias])) {
  271. $first = reset($this->_resultPointers);
  272. $parentObject = $first[key($first)];
  273. } else if (isset($this->_resultPointers[$parentAlias])) {
  274. $parentObject = $this->_resultPointers[$parentAlias];
  275. } else {
  276. // Parent object of relation not found, so skip it.
  277. continue;
  278. }
  279. $parentClass = $this->_ce[$this->_rsm->aliasMap[$parentAlias]];
  280. $oid = spl_object_hash($parentObject);
  281. $relationField = $this->_rsm->relationMap[$dqlAlias];
  282. $relation = $parentClass->associationMappings[$relationField];
  283. $reflField = $parentClass->reflFields[$relationField];
  284. // Check the type of the relation (many or single-valued)
  285. if ( ! ($relation['type'] & ClassMetadata::TO_ONE)) {
  286. $reflFieldValue = $reflField->getValue($parentObject);
  287. // PATH A: Collection-valued association
  288. if (isset($nonemptyComponents[$dqlAlias])) {
  289. $collKey = $oid . $relationField;
  290. if (isset($this->_initializedCollections[$collKey])) {
  291. $reflFieldValue = $this->_initializedCollections[$collKey];
  292. } else if ( ! isset($this->_existingCollections[$collKey])) {
  293. $reflFieldValue = $this->_initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias);
  294. }
  295. $indexExists = isset($this->_identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]]);
  296. $index = $indexExists ? $this->_identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] : false;
  297. $indexIsValid = $index !== false ? isset($reflFieldValue[$index]) : false;
  298. if ( ! $indexExists || ! $indexIsValid) {
  299. if (isset($this->_existingCollections[$collKey])) {
  300. // Collection exists, only look for the element in the identity map.
  301. if ($element = $this->_getEntityFromIdentityMap($entityName, $data)) {
  302. $this->_resultPointers[$dqlAlias] = $element;
  303. } else {
  304. unset($this->_resultPointers[$dqlAlias]);
  305. }
  306. } else {
  307. $element = $this->_getEntity($data, $dqlAlias);
  308. if (isset($this->_rsm->indexByMap[$dqlAlias])) {
  309. $field = $this->_rsm->indexByMap[$dqlAlias];
  310. $indexValue = $this->_ce[$entityName]->reflFields[$field]->getValue($element);
  311. $reflFieldValue->hydrateSet($indexValue, $element);
  312. $this->_identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] = $indexValue;
  313. } else {
  314. $reflFieldValue->hydrateAdd($element);
  315. $reflFieldValue->last();
  316. $this->_identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] = $reflFieldValue->key();
  317. }
  318. // Update result pointer
  319. $this->_resultPointers[$dqlAlias] = $element;
  320. }
  321. } else {
  322. // Update result pointer
  323. $this->_resultPointers[$dqlAlias] = $reflFieldValue[$index];
  324. }
  325. } else if ( ! $reflFieldValue) {
  326. $reflFieldValue = $this->_initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias);
  327. } else if ($reflFieldValue instanceof PersistentCollection && $reflFieldValue->isInitialized() === false) {
  328. $reflFieldValue->setInitialized(true);
  329. }
  330. } else {
  331. // PATH B: Single-valued association
  332. $reflFieldValue = $reflField->getValue($parentObject);
  333. if ( ! $reflFieldValue || isset($this->_hints[Query::HINT_REFRESH]) || ($reflFieldValue instanceof Proxy && !$reflFieldValue->__isInitialized__)) {
  334. // we only need to take action if this value is null,
  335. // we refresh the entity or its an unitialized proxy.
  336. if (isset($nonemptyComponents[$dqlAlias])) {
  337. $element = $this->_getEntity($data, $dqlAlias);
  338. $reflField->setValue($parentObject, $element);
  339. $this->_uow->setOriginalEntityProperty($oid, $relationField, $element);
  340. $targetClass = $this->_ce[$relation['targetEntity']];
  341. if ($relation['isOwningSide']) {
  342. //TODO: Just check hints['fetched'] here?
  343. // If there is an inverse mapping on the target class its bidirectional
  344. if ($relation['inversedBy']) {
  345. $inverseAssoc = $targetClass->associationMappings[$relation['inversedBy']];
  346. if ($inverseAssoc['type'] & ClassMetadata::TO_ONE) {
  347. $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($element, $parentObject);
  348. $this->_uow->setOriginalEntityProperty(spl_object_hash($element), $inverseAssoc['fieldName'], $parentObject);
  349. }
  350. } else if ($parentClass === $targetClass && $relation['mappedBy']) {
  351. // Special case: bi-directional self-referencing one-one on the same class
  352. $targetClass->reflFields[$relationField]->setValue($element, $parentObject);
  353. }
  354. } else {
  355. // For sure bidirectional, as there is no inverse side in unidirectional mappings
  356. $targetClass->reflFields[$relation['mappedBy']]->setValue($element, $parentObject);
  357. $this->_uow->setOriginalEntityProperty(spl_object_hash($element), $relation['mappedBy'], $parentObject);
  358. }
  359. // Update result pointer
  360. $this->_resultPointers[$dqlAlias] = $element;
  361. } else {
  362. $this->_uow->setOriginalEntityProperty($oid, $relationField, null);
  363. }
  364. // else leave $reflFieldValue null for single-valued associations
  365. } else {
  366. // Update result pointer
  367. $this->_resultPointers[$dqlAlias] = $reflFieldValue;
  368. }
  369. }
  370. } else {
  371. // PATH C: Its a root result element
  372. $this->_rootAliases[$dqlAlias] = true; // Mark as root alias
  373. // if this row has a NULL value for the root result id then make it a null result.
  374. if ( ! isset($nonemptyComponents[$dqlAlias]) ) {
  375. if ($this->_rsm->isMixed) {
  376. $result[] = array(0 => null);
  377. } else {
  378. $result[] = null;
  379. }
  380. ++$this->_resultCounter;
  381. continue;
  382. }
  383. // check for existing result from the iterations before
  384. if ( ! isset($this->_identifierMap[$dqlAlias][$id[$dqlAlias]])) {
  385. $element = $this->_getEntity($rowData[$dqlAlias], $dqlAlias);
  386. if (isset($this->_rsm->indexByMap[$dqlAlias])) {
  387. $field = $this->_rsm->indexByMap[$dqlAlias];
  388. $key = $this->_ce[$entityName]->reflFields[$field]->getValue($element);
  389. if ($this->_rsm->isMixed) {
  390. $element = array($key => $element);
  391. $result[] = $element;
  392. $this->_identifierMap[$dqlAlias][$id[$dqlAlias]] = $this->_resultCounter;
  393. ++$this->_resultCounter;
  394. } else {
  395. $result[$key] = $element;
  396. $this->_identifierMap[$dqlAlias][$id[$dqlAlias]] = $key;
  397. }
  398. if (isset($this->_hints['collection'])) {
  399. $this->_hints['collection']->hydrateSet($key, $element);
  400. }
  401. } else {
  402. if ($this->_rsm->isMixed) {
  403. $element = array(0 => $element);
  404. }
  405. $result[] = $element;
  406. $this->_identifierMap[$dqlAlias][$id[$dqlAlias]] = $this->_resultCounter;
  407. ++$this->_resultCounter;
  408. if (isset($this->_hints['collection'])) {
  409. $this->_hints['collection']->hydrateAdd($element);
  410. }
  411. }
  412. // Update result pointer
  413. $this->_resultPointers[$dqlAlias] = $element;
  414. } else {
  415. // Update result pointer
  416. $index = $this->_identifierMap[$dqlAlias][$id[$dqlAlias]];
  417. $this->_resultPointers[$dqlAlias] = $result[$index];
  418. /*if ($this->_rsm->isMixed) {
  419. $result[] = $result[$index];
  420. ++$this->_resultCounter;
  421. }*/
  422. }
  423. }
  424. }
  425. // Append scalar values to mixed result sets
  426. if (isset($scalars)) {
  427. foreach ($scalars as $name => $value) {
  428. $result[$this->_resultCounter - 1][$name] = $value;
  429. }
  430. }
  431. }
  432. }