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

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