ObjectHydrator.php 23 KB

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