ObjectHydrator.php 23 KB

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