vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 319

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM\Internal\Hydration;
  4. use Doctrine\Common\Collections\ArrayCollection;
  5. use Doctrine\Common\Proxy\Proxy;
  6. use Doctrine\ORM\Mapping\ClassMetadata;
  7. use Doctrine\ORM\PersistentCollection;
  8. use Doctrine\ORM\Query;
  9. use Doctrine\ORM\UnitOfWork;
  10. use function array_fill_keys;
  11. use function array_keys;
  12. use function count;
  13. use function is_array;
  14. use function key;
  15. use function ltrim;
  16. use function spl_object_id;
  17. /**
  18.  * The ObjectHydrator constructs an object graph out of an SQL result set.
  19.  *
  20.  * Internal note: Highly performance-sensitive code.
  21.  */
  22. class ObjectHydrator extends AbstractHydrator
  23. {
  24.     /** @var mixed[] */
  25.     private $identifierMap = [];
  26.     /** @var mixed[] */
  27.     private $resultPointers = [];
  28.     /** @var mixed[] */
  29.     private $idTemplate = [];
  30.     /** @var int */
  31.     private $resultCounter 0;
  32.     /** @var mixed[] */
  33.     private $rootAliases = [];
  34.     /** @var mixed[] */
  35.     private $initializedCollections = [];
  36.     /** @var array<string, PersistentCollection> */
  37.     private $uninitializedCollections = [];
  38.     /** @var mixed[] */
  39.     private $existingCollections = [];
  40.     /**
  41.      * {@inheritdoc}
  42.      */
  43.     protected function prepare()
  44.     {
  45.         if (! isset($this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD])) {
  46.             $this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD] = true;
  47.         }
  48.         foreach ($this->resultSetMapping()->aliasMap as $dqlAlias => $className) {
  49.             $this->identifierMap[$dqlAlias] = [];
  50.             $this->idTemplate[$dqlAlias]    = '';
  51.             // Remember which associations are "fetch joined", so that we know where to inject
  52.             // collection stubs or proxies and where not.
  53.             if (! isset($this->resultSetMapping()->relationMap[$dqlAlias])) {
  54.                 continue;
  55.             }
  56.             $parent $this->resultSetMapping()->parentAliasMap[$dqlAlias];
  57.             if (! isset($this->resultSetMapping()->aliasMap[$parent])) {
  58.                 throw HydrationException::parentObjectOfRelationNotFound($dqlAlias$parent);
  59.             }
  60.             $sourceClassName $this->resultSetMapping()->aliasMap[$parent];
  61.             $sourceClass     $this->getClassMetadata($sourceClassName);
  62.             $assoc           $sourceClass->associationMappings[$this->resultSetMapping()->relationMap[$dqlAlias]];
  63.             $this->_hints['fetched'][$parent][$assoc['fieldName']] = true;
  64.             if ($assoc['type'] === ClassMetadata::MANY_TO_MANY) {
  65.                 continue;
  66.             }
  67.             // Mark any non-collection opposite sides as fetched, too.
  68.             if ($assoc['mappedBy']) {
  69.                 $this->_hints['fetched'][$dqlAlias][$assoc['mappedBy']] = true;
  70.                 continue;
  71.             }
  72.             // handle fetch-joined owning side bi-directional one-to-one associations
  73.             if ($assoc['inversedBy']) {
  74.                 $class        $this->getClassMetadata($className);
  75.                 $inverseAssoc $class->associationMappings[$assoc['inversedBy']];
  76.                 if (! ($inverseAssoc['type'] & ClassMetadata::TO_ONE)) {
  77.                     continue;
  78.                 }
  79.                 $this->_hints['fetched'][$dqlAlias][$inverseAssoc['fieldName']] = true;
  80.             }
  81.         }
  82.     }
  83.     /**
  84.      * {@inheritdoc}
  85.      */
  86.     protected function cleanup()
  87.     {
  88.         $eagerLoad = isset($this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD]) && $this->_hints[UnitOfWork::HINT_DEFEREAGERLOAD] === true;
  89.         parent::cleanup();
  90.         $this->identifierMap            =
  91.         $this->initializedCollections   =
  92.         $this->uninitializedCollections =
  93.         $this->existingCollections      =
  94.         $this->resultPointers           = [];
  95.         if ($eagerLoad) {
  96.             $this->_uow->triggerEagerLoads();
  97.         }
  98.         $this->_uow->hydrationComplete();
  99.     }
  100.     protected function cleanupAfterRowIteration(): void
  101.     {
  102.         $this->identifierMap            =
  103.         $this->initializedCollections   =
  104.         $this->uninitializedCollections =
  105.         $this->existingCollections      =
  106.         $this->resultPointers           = [];
  107.     }
  108.     /**
  109.      * {@inheritdoc}
  110.      */
  111.     protected function hydrateAllData()
  112.     {
  113.         $result = [];
  114.         while ($row $this->statement()->fetchAssociative()) {
  115.             $this->hydrateRowData($row$result);
  116.         }
  117.         // Take snapshots from all newly initialized collections
  118.         foreach ($this->initializedCollections as $coll) {
  119.             $coll->takeSnapshot();
  120.         }
  121.         foreach ($this->uninitializedCollections as $coll) {
  122.             if (! $coll->isInitialized()) {
  123.                 $coll->setInitialized(true);
  124.             }
  125.         }
  126.         return $result;
  127.     }
  128.     /**
  129.      * Initializes a related collection.
  130.      *
  131.      * @param object $entity         The entity to which the collection belongs.
  132.      * @param string $fieldName      The name of the field on the entity that holds the collection.
  133.      * @param string $parentDqlAlias Alias of the parent fetch joining this collection.
  134.      */
  135.     private function initRelatedCollection(
  136.         $entity,
  137.         ClassMetadata $class,
  138.         string $fieldName,
  139.         string $parentDqlAlias
  140.     ): PersistentCollection {
  141.         $oid      spl_object_id($entity);
  142.         $relation $class->associationMappings[$fieldName];
  143.         $value    $class->reflFields[$fieldName]->getValue($entity);
  144.         if ($value === null || is_array($value)) {
  145.             $value = new ArrayCollection((array) $value);
  146.         }
  147.         if (! $value instanceof PersistentCollection) {
  148.             $value = new PersistentCollection(
  149.                 $this->_em,
  150.                 $this->_metadataCache[$relation['targetEntity']],
  151.                 $value
  152.             );
  153.             $value->setOwner($entity$relation);
  154.             $class->reflFields[$fieldName]->setValue($entity$value);
  155.             $this->_uow->setOriginalEntityProperty($oid$fieldName$value);
  156.             $this->initializedCollections[$oid $fieldName] = $value;
  157.         } elseif (
  158.             isset($this->_hints[Query::HINT_REFRESH]) ||
  159.             isset($this->_hints['fetched'][$parentDqlAlias][$fieldName]) &&
  160.              ! $value->isInitialized()
  161.         ) {
  162.             // Is already PersistentCollection, but either REFRESH or FETCH-JOIN and UNINITIALIZED!
  163.             $value->setDirty(false);
  164.             $value->setInitialized(true);
  165.             $value->unwrap()->clear();
  166.             $this->initializedCollections[$oid $fieldName] = $value;
  167.         } else {
  168.             // Is already PersistentCollection, and DON'T REFRESH or FETCH-JOIN!
  169.             $this->existingCollections[$oid $fieldName] = $value;
  170.         }
  171.         return $value;
  172.     }
  173.     /**
  174.      * Gets an entity instance.
  175.      *
  176.      * @param string $dqlAlias The DQL alias of the entity's class.
  177.      * @psalm-param array<string, mixed> $data     The instance data.
  178.      *
  179.      * @return object
  180.      *
  181.      * @throws HydrationException
  182.      */
  183.     private function getEntity(array $datastring $dqlAlias)
  184.     {
  185.         $className $this->resultSetMapping()->aliasMap[$dqlAlias];
  186.         if (isset($this->resultSetMapping()->discriminatorColumns[$dqlAlias])) {
  187.             $fieldName $this->resultSetMapping()->discriminatorColumns[$dqlAlias];
  188.             if (! isset($this->resultSetMapping()->metaMappings[$fieldName])) {
  189.                 throw HydrationException::missingDiscriminatorMetaMappingColumn($className$fieldName$dqlAlias);
  190.             }
  191.             $discrColumn $this->resultSetMapping()->metaMappings[$fieldName];
  192.             if (! isset($data[$discrColumn])) {
  193.                 throw HydrationException::missingDiscriminatorColumn($className$discrColumn$dqlAlias);
  194.             }
  195.             if ($data[$discrColumn] === '') {
  196.                 throw HydrationException::emptyDiscriminatorValue($dqlAlias);
  197.             }
  198.             $discrMap           $this->_metadataCache[$className]->discriminatorMap;
  199.             $discriminatorValue = (string) $data[$discrColumn];
  200.             if (! isset($discrMap[$discriminatorValue])) {
  201.                 throw HydrationException::invalidDiscriminatorValue($discriminatorValuearray_keys($discrMap));
  202.             }
  203.             $className $discrMap[$discriminatorValue];
  204.             unset($data[$discrColumn]);
  205.         }
  206.         if (isset($this->_hints[Query::HINT_REFRESH_ENTITY], $this->rootAliases[$dqlAlias])) {
  207.             $this->registerManaged($this->_metadataCache[$className], $this->_hints[Query::HINT_REFRESH_ENTITY], $data);
  208.         }
  209.         $this->_hints['fetchAlias'] = $dqlAlias;
  210.         return $this->_uow->createEntity($className$data$this->_hints);
  211.     }
  212.     /**
  213.      * @psalm-param class-string $className
  214.      * @psalm-param array<string, mixed> $data
  215.      *
  216.      * @return mixed
  217.      */
  218.     private function getEntityFromIdentityMap(string $className, array $data)
  219.     {
  220.         // TODO: Abstract this code and UnitOfWork::createEntity() equivalent?
  221.         $class $this->_metadataCache[$className];
  222.         if ($class->isIdentifierComposite) {
  223.             $idHash '';
  224.             foreach ($class->identifier as $fieldName) {
  225.                 $idHash .= ' ' . (isset($class->associationMappings[$fieldName])
  226.                     ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
  227.                     : $data[$fieldName]);
  228.             }
  229.             return $this->_uow->tryGetByIdHash(ltrim($idHash), $class->rootEntityName);
  230.         } elseif (isset($class->associationMappings[$class->identifier[0]])) {
  231.             return $this->_uow->tryGetByIdHash($data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']], $class->rootEntityName);
  232.         }
  233.         return $this->_uow->tryGetByIdHash($data[$class->identifier[0]], $class->rootEntityName);
  234.     }
  235.     /**
  236.      * Hydrates a single row in an SQL result set.
  237.      *
  238.      * @internal
  239.      * First, the data of the row is split into chunks where each chunk contains data
  240.      * that belongs to a particular component/class. Afterwards, all these chunks
  241.      * are processed, one after the other. For each chunk of class data only one of the
  242.      * following code paths is executed:
  243.      *
  244.      * Path A: The data chunk belongs to a joined/associated object and the association
  245.      *         is collection-valued.
  246.      * Path B: The data chunk belongs to a joined/associated object and the association
  247.      *         is single-valued.
  248.      * Path C: The data chunk belongs to a root result element/object that appears in the topmost
  249.      *         level of the hydrated result. A typical example are the objects of the type
  250.      *         specified by the FROM clause in a DQL query.
  251.      *
  252.      * @param mixed[] $row    The data of the row to process.
  253.      * @param mixed[] $result The result array to fill.
  254.      *
  255.      * @return void
  256.      */
  257.     protected function hydrateRowData(array $row, array &$result)
  258.     {
  259.         // Initialize
  260.         $id                 $this->idTemplate// initialize the id-memory
  261.         $nonemptyComponents = [];
  262.         // Split the row data into chunks of class data.
  263.         $rowData $this->gatherRowData($row$id$nonemptyComponents);
  264.         // reset result pointers for each data row
  265.         $this->resultPointers = [];
  266.         // Hydrate the data chunks
  267.         foreach ($rowData['data'] as $dqlAlias => $data) {
  268.             $entityName $this->resultSetMapping()->aliasMap[$dqlAlias];
  269.             if (isset($this->resultSetMapping()->parentAliasMap[$dqlAlias])) {
  270.                 // It's a joined result
  271.                 $parentAlias $this->resultSetMapping()->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.                 $parentClass   $this->_metadataCache[$this->resultSetMapping()->aliasMap[$parentAlias]];
  281.                 $relationField $this->resultSetMapping()->relationMap[$dqlAlias];
  282.                 $relation      $parentClass->associationMappings[$relationField];
  283.                 $reflField     $parentClass->reflFields[$relationField];
  284.                 // Get a reference to the parent object to which the joined element belongs.
  285.                 if ($this->resultSetMapping()->isMixed && isset($this->rootAliases[$parentAlias])) {
  286.                     $objectClass  $this->resultPointers[$parentAlias];
  287.                     $parentObject $objectClass[key($objectClass)];
  288.                 } elseif (isset($this->resultPointers[$parentAlias])) {
  289.                     $parentObject $this->resultPointers[$parentAlias];
  290.                 } else {
  291.                     // Parent object of relation not found, mark as not-fetched again
  292.                     $element $this->getEntity($data$dqlAlias);
  293.                     // Update result pointer and provide initial fetch data for parent
  294.                     $this->resultPointers[$dqlAlias]               = $element;
  295.                     $rowData['data'][$parentAlias][$relationField] = $element;
  296.                     // Mark as not-fetched again
  297.                     unset($this->_hints['fetched'][$parentAlias][$relationField]);
  298.                     continue;
  299.                 }
  300.                 $oid spl_object_id($parentObject);
  301.                 // Check the type of the relation (many or single-valued)
  302.                 if (! ($relation['type'] & ClassMetadata::TO_ONE)) {
  303.                     // PATH A: Collection-valued association
  304.                     $reflFieldValue $reflField->getValue($parentObject);
  305.                     if (isset($nonemptyComponents[$dqlAlias])) {
  306.                         $collKey $oid $relationField;
  307.                         if (isset($this->initializedCollections[$collKey])) {
  308.                             $reflFieldValue $this->initializedCollections[$collKey];
  309.                         } elseif (! isset($this->existingCollections[$collKey])) {
  310.                             $reflFieldValue $this->initRelatedCollection($parentObject$parentClass$relationField$parentAlias);
  311.                         }
  312.                         $indexExists  = isset($this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]]);
  313.                         $index        $indexExists $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] : false;
  314.                         $indexIsValid $index !== false ? isset($reflFieldValue[$index]) : false;
  315.                         if (! $indexExists || ! $indexIsValid) {
  316.                             if (isset($this->existingCollections[$collKey])) {
  317.                                 // Collection exists, only look for the element in the identity map.
  318.                                 $element $this->getEntityFromIdentityMap($entityName$data);
  319.                                 if ($element) {
  320.                                     $this->resultPointers[$dqlAlias] = $element;
  321.                                 } else {
  322.                                     unset($this->resultPointers[$dqlAlias]);
  323.                                 }
  324.                             } else {
  325.                                 $element $this->getEntity($data$dqlAlias);
  326.                                 if (isset($this->resultSetMapping()->indexByMap[$dqlAlias])) {
  327.                                     $indexValue $row[$this->resultSetMapping()->indexByMap[$dqlAlias]];
  328.                                     $reflFieldValue->hydrateSet($indexValue$element);
  329.                                     $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] = $indexValue;
  330.                                 } else {
  331.                                     if (! $reflFieldValue->contains($element)) {
  332.                                         $reflFieldValue->hydrateAdd($element);
  333.                                         $reflFieldValue->last();
  334.                                     }
  335.                                     $this->identifierMap[$path][$id[$parentAlias]][$id[$dqlAlias]] = $reflFieldValue->key();
  336.                                 }
  337.                                 // Update result pointer
  338.                                 $this->resultPointers[$dqlAlias] = $element;
  339.                             }
  340.                         } else {
  341.                             // Update result pointer
  342.                             $this->resultPointers[$dqlAlias] = $reflFieldValue[$index];
  343.                         }
  344.                     } elseif (! $reflFieldValue) {
  345.                         $this->initRelatedCollection($parentObject$parentClass$relationField$parentAlias);
  346.                     } elseif ($reflFieldValue instanceof PersistentCollection && $reflFieldValue->isInitialized() === false && ! isset($this->uninitializedCollections[$oid $relationField])) {
  347.                         $this->uninitializedCollections[$oid $relationField] = $reflFieldValue;
  348.                     }
  349.                 } else {
  350.                     // PATH B: Single-valued association
  351.                     $reflFieldValue $reflField->getValue($parentObject);
  352.                     if (! $reflFieldValue || isset($this->_hints[Query::HINT_REFRESH]) || ($reflFieldValue instanceof Proxy && ! $reflFieldValue->__isInitialized())) {
  353.                         // we only need to take action if this value is null,
  354.                         // we refresh the entity or its an uninitialized proxy.
  355.                         if (isset($nonemptyComponents[$dqlAlias])) {
  356.                             $element $this->getEntity($data$dqlAlias);
  357.                             $reflField->setValue($parentObject$element);
  358.                             $this->_uow->setOriginalEntityProperty($oid$relationField$element);
  359.                             $targetClass $this->_metadataCache[$relation['targetEntity']];
  360.                             if ($relation['isOwningSide']) {
  361.                                 // TODO: Just check hints['fetched'] here?
  362.                                 // If there is an inverse mapping on the target class its bidirectional
  363.                                 if ($relation['inversedBy']) {
  364.                                     $inverseAssoc $targetClass->associationMappings[$relation['inversedBy']];
  365.                                     if ($inverseAssoc['type'] & ClassMetadata::TO_ONE) {
  366.                                         $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($element$parentObject);
  367.                                         $this->_uow->setOriginalEntityProperty(spl_object_id($element), $inverseAssoc['fieldName'], $parentObject);
  368.                                     }
  369.                                 } elseif ($parentClass === $targetClass && $relation['mappedBy']) {
  370.                                     // Special case: bi-directional self-referencing one-one on the same class
  371.                                     $targetClass->reflFields[$relationField]->setValue($element$parentObject);
  372.                                 }
  373.                             } else {
  374.                                 // For sure bidirectional, as there is no inverse side in unidirectional mappings
  375.                                 $targetClass->reflFields[$relation['mappedBy']]->setValue($element$parentObject);
  376.                                 $this->_uow->setOriginalEntityProperty(spl_object_id($element), $relation['mappedBy'], $parentObject);
  377.                             }
  378.                             // Update result pointer
  379.                             $this->resultPointers[$dqlAlias] = $element;
  380.                         } else {
  381.                             $this->_uow->setOriginalEntityProperty($oid$relationFieldnull);
  382.                             $reflField->setValue($parentObjectnull);
  383.                         }
  384.                         // else leave $reflFieldValue null for single-valued associations
  385.                     } else {
  386.                         // Update result pointer
  387.                         $this->resultPointers[$dqlAlias] = $reflFieldValue;
  388.                     }
  389.                 }
  390.             } else {
  391.                 // PATH C: Its a root result element
  392.                 $this->rootAliases[$dqlAlias] = true// Mark as root alias
  393.                 $entityKey                    $this->resultSetMapping()->entityMappings[$dqlAlias] ?: 0;
  394.                 // if this row has a NULL value for the root result id then make it a null result.
  395.                 if (! isset($nonemptyComponents[$dqlAlias])) {
  396.                     if ($this->resultSetMapping()->isMixed) {
  397.                         $result[] = [$entityKey => null];
  398.                     } else {
  399.                         $result[] = null;
  400.                     }
  401.                     $resultKey $this->resultCounter;
  402.                     ++$this->resultCounter;
  403.                     continue;
  404.                 }
  405.                 // check for existing result from the iterations before
  406.                 if (! isset($this->identifierMap[$dqlAlias][$id[$dqlAlias]])) {
  407.                     $element $this->getEntity($data$dqlAlias);
  408.                     if ($this->resultSetMapping()->isMixed) {
  409.                         $element = [$entityKey => $element];
  410.                     }
  411.                     if (isset($this->resultSetMapping()->indexByMap[$dqlAlias])) {
  412.                         $resultKey $row[$this->resultSetMapping()->indexByMap[$dqlAlias]];
  413.                         if (isset($this->_hints['collection'])) {
  414.                             $this->_hints['collection']->hydrateSet($resultKey$element);
  415.                         }
  416.                         $result[$resultKey] = $element;
  417.                     } else {
  418.                         $resultKey $this->resultCounter;
  419.                         ++$this->resultCounter;
  420.                         if (isset($this->_hints['collection'])) {
  421.                             $this->_hints['collection']->hydrateAdd($element);
  422.                         }
  423.                         $result[] = $element;
  424.                     }
  425.                     $this->identifierMap[$dqlAlias][$id[$dqlAlias]] = $resultKey;
  426.                     // Update result pointer
  427.                     $this->resultPointers[$dqlAlias] = $element;
  428.                 } else {
  429.                     // Update result pointer
  430.                     $index                           $this->identifierMap[$dqlAlias][$id[$dqlAlias]];
  431.                     $this->resultPointers[$dqlAlias] = $result[$index];
  432.                     $resultKey                       $index;
  433.                 }
  434.             }
  435.             if (isset($this->_hints[Query::HINT_INTERNAL_ITERATION]) && $this->_hints[Query::HINT_INTERNAL_ITERATION]) {
  436.                 $this->_uow->hydrationComplete();
  437.             }
  438.         }
  439.         if (! isset($resultKey)) {
  440.             $this->resultCounter++;
  441.         }
  442.         // Append scalar values to mixed result sets
  443.         if (isset($rowData['scalars'])) {
  444.             if (! isset($resultKey)) {
  445.                 $resultKey = isset($this->resultSetMapping()->indexByMap['scalars'])
  446.                     ? $row[$this->resultSetMapping()->indexByMap['scalars']]
  447.                     : $this->resultCounter 1;
  448.             }
  449.             foreach ($rowData['scalars'] as $name => $value) {
  450.                 $result[$resultKey][$name] = $value;
  451.             }
  452.         }
  453.         // Append new object to mixed result sets
  454.         if (isset($rowData['newObjects'])) {
  455.             if (! isset($resultKey)) {
  456.                 $resultKey $this->resultCounter 1;
  457.             }
  458.             $scalarCount = (isset($rowData['scalars']) ? count($rowData['scalars']) : 0);
  459.             foreach ($rowData['newObjects'] as $objIndex => $newObject) {
  460.                 $class $newObject['class'];
  461.                 $args  $newObject['args'];
  462.                 $obj   $class->newInstanceArgs($args);
  463.                 if ($scalarCount === && count($rowData['newObjects']) === 1) {
  464.                     $result[$resultKey] = $obj;
  465.                     continue;
  466.                 }
  467.                 $result[$resultKey][$objIndex] = $obj;
  468.             }
  469.         }
  470.     }
  471.     /**
  472.      * When executed in a hydrate() loop we may have to clear internal state to
  473.      * decrease memory consumption.
  474.      *
  475.      * @param mixed $eventArgs
  476.      *
  477.      * @return void
  478.      */
  479.     public function onClear($eventArgs)
  480.     {
  481.         parent::onClear($eventArgs);
  482.         $aliases array_keys($this->identifierMap);
  483.         $this->identifierMap array_fill_keys($aliases, []);
  484.     }
  485. }