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