vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php line 152

Open in your IDE?
  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. namespace Doctrine\ORM\Internal\Hydration;
  20. use Doctrine\DBAL\Types\Type;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Doctrine\ORM\Events;
  23. use Doctrine\ORM\Mapping\ClassMetadata;
  24. use PDO;
  25. use function array_map;
  26. use function in_array;
  27. /**
  28.  * Base class for all hydrators. A hydrator is a class that provides some form
  29.  * of transformation of an SQL result set into another structure.
  30.  *
  31.  * @since  2.0
  32.  * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  33.  * @author Roman Borschel <roman@code-factory.org>
  34.  * @author Guilherme Blanco <guilhermeblanoc@hotmail.com>
  35.  */
  36. abstract class AbstractHydrator
  37. {
  38.     /**
  39.      * The ResultSetMapping.
  40.      *
  41.      * @var \Doctrine\ORM\Query\ResultSetMapping
  42.      */
  43.     protected $_rsm;
  44.     /**
  45.      * The EntityManager instance.
  46.      *
  47.      * @var EntityManagerInterface
  48.      */
  49.     protected $_em;
  50.     /**
  51.      * The dbms Platform instance.
  52.      *
  53.      * @var \Doctrine\DBAL\Platforms\AbstractPlatform
  54.      */
  55.     protected $_platform;
  56.     /**
  57.      * The UnitOfWork of the associated EntityManager.
  58.      *
  59.      * @var \Doctrine\ORM\UnitOfWork
  60.      */
  61.     protected $_uow;
  62.     /**
  63.      * Local ClassMetadata cache to avoid going to the EntityManager all the time.
  64.      *
  65.      * @var array
  66.      */
  67.     protected $_metadataCache = [];
  68.     /**
  69.      * The cache used during row-by-row hydration.
  70.      *
  71.      * @var array
  72.      */
  73.     protected $_cache = [];
  74.     /**
  75.      * The statement that provides the data to hydrate.
  76.      *
  77.      * @var \Doctrine\DBAL\Driver\Statement
  78.      */
  79.     protected $_stmt;
  80.     /**
  81.      * The query hints.
  82.      *
  83.      * @var array
  84.      */
  85.     protected $_hints;
  86.     /**
  87.      * Initializes a new instance of a class derived from <tt>AbstractHydrator</tt>.
  88.      *
  89.      * @param EntityManagerInterface $em The EntityManager to use.
  90.      */
  91.     public function __construct(EntityManagerInterface $em)
  92.     {
  93.         $this->_em       $em;
  94.         $this->_platform $em->getConnection()->getDatabasePlatform();
  95.         $this->_uow      $em->getUnitOfWork();
  96.     }
  97.     /**
  98.      * Initiates a row-by-row hydration.
  99.      *
  100.      * @param object $stmt
  101.      * @param object $resultSetMapping
  102.      * @param array  $hints
  103.      *
  104.      * @return IterableResult
  105.      */
  106.     public function iterate($stmt$resultSetMapping, array $hints = [])
  107.     {
  108.         $this->_stmt  $stmt;
  109.         $this->_rsm   $resultSetMapping;
  110.         $this->_hints $hints;
  111.         $evm $this->_em->getEventManager();
  112.         $evm->addEventListener([Events::onClear], $this);
  113.         $this->prepare();
  114.         return new IterableResult($this);
  115.     }
  116.     /**
  117.      * Hydrates all rows returned by the passed statement instance at once.
  118.      *
  119.      * @param object $stmt
  120.      * @param object $resultSetMapping
  121.      * @param array  $hints
  122.      *
  123.      * @return array
  124.      */
  125.     public function hydrateAll($stmt$resultSetMapping, array $hints = [])
  126.     {
  127.         $this->_stmt  $stmt;
  128.         $this->_rsm   $resultSetMapping;
  129.         $this->_hints $hints;
  130.         $this->_em->getEventManager()->addEventListener([Events::onClear], $this);
  131.         $this->prepare();
  132.         $result $this->hydrateAllData();
  133.         $this->cleanup();
  134.         return $result;
  135.     }
  136.     /**
  137.      * Hydrates a single row returned by the current statement instance during
  138.      * row-by-row hydration with {@link iterate()}.
  139.      *
  140.      * @return mixed
  141.      */
  142.     public function hydrateRow()
  143.     {
  144.         $row $this->_stmt->fetch(PDO::FETCH_ASSOC);
  145.         if ( ! $row) {
  146.             $this->cleanup();
  147.             return false;
  148.         }
  149.         $result = [];
  150.         $this->hydrateRowData($row$result);
  151.         return $result;
  152.     }
  153.     /**
  154.      * When executed in a hydrate() loop we have to clear internal state to
  155.      * decrease memory consumption.
  156.      *
  157.      * @param mixed $eventArgs
  158.      *
  159.      * @return void
  160.      */
  161.     public function onClear($eventArgs)
  162.     {
  163.     }
  164.     /**
  165.      * Executes one-time preparation tasks, once each time hydration is started
  166.      * through {@link hydrateAll} or {@link iterate()}.
  167.      *
  168.      * @return void
  169.      */
  170.     protected function prepare()
  171.     {
  172.     }
  173.     /**
  174.      * Executes one-time cleanup tasks at the end of a hydration that was initiated
  175.      * through {@link hydrateAll} or {@link iterate()}.
  176.      *
  177.      * @return void
  178.      */
  179.     protected function cleanup()
  180.     {
  181.         $this->_stmt->closeCursor();
  182.         $this->_stmt          null;
  183.         $this->_rsm           null;
  184.         $this->_cache         = [];
  185.         $this->_metadataCache = [];
  186.         $this
  187.             ->_em
  188.             ->getEventManager()
  189.             ->removeEventListener([Events::onClear], $this);
  190.     }
  191.     /**
  192.      * Hydrates a single row from the current statement instance.
  193.      *
  194.      * Template method.
  195.      *
  196.      * @param array $data   The row data.
  197.      * @param array $result The result to fill.
  198.      *
  199.      * @return void
  200.      *
  201.      * @throws HydrationException
  202.      */
  203.     protected function hydrateRowData(array $data, array &$result)
  204.     {
  205.         throw new HydrationException("hydrateRowData() not implemented by this hydrator.");
  206.     }
  207.     /**
  208.      * Hydrates all rows from the current statement instance at once.
  209.      *
  210.      * @return array
  211.      */
  212.     abstract protected function hydrateAllData();
  213.     /**
  214.      * Processes a row of the result set.
  215.      *
  216.      * Used for identity-based hydration (HYDRATE_OBJECT and HYDRATE_ARRAY).
  217.      * Puts the elements of a result row into a new array, grouped by the dql alias
  218.      * they belong to. The column names in the result set are mapped to their
  219.      * field names during this procedure as well as any necessary conversions on
  220.      * the values applied. Scalar values are kept in a specific key 'scalars'.
  221.      *
  222.      * @param array  $data               SQL Result Row.
  223.      * @param array &$id                 Dql-Alias => ID-Hash.
  224.      * @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value?
  225.      *
  226.      * @return array  An array with all the fields (name => value) of the data row,
  227.      *                grouped by their component alias.
  228.      */
  229.     protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents)
  230.     {
  231.         $rowData = ['data' => []];
  232.         foreach ($data as $key => $value) {
  233.             if (($cacheKeyInfo $this->hydrateColumnInfo($key)) === null) {
  234.                 continue;
  235.             }
  236.             $fieldName $cacheKeyInfo['fieldName'];
  237.             switch (true) {
  238.                 case (isset($cacheKeyInfo['isNewObjectParameter'])):
  239.                     $argIndex $cacheKeyInfo['argIndex'];
  240.                     $objIndex $cacheKeyInfo['objIndex'];
  241.                     $type     $cacheKeyInfo['type'];
  242.                     $value    $type->convertToPHPValue($value$this->_platform);
  243.                     $rowData['newObjects'][$objIndex]['class']           = $cacheKeyInfo['class'];
  244.                     $rowData['newObjects'][$objIndex]['args'][$argIndex] = $value;
  245.                     break;
  246.                 case (isset($cacheKeyInfo['isScalar'])):
  247.                     $type  $cacheKeyInfo['type'];
  248.                     $value $type->convertToPHPValue($value$this->_platform);
  249.                     $rowData['scalars'][$fieldName] = $value;
  250.                     break;
  251.                 //case (isset($cacheKeyInfo['isMetaColumn'])):
  252.                 default:
  253.                     $dqlAlias $cacheKeyInfo['dqlAlias'];
  254.                     $type     $cacheKeyInfo['type'];
  255.                     // If there are field name collisions in the child class, then we need
  256.                     // to only hydrate if we are looking at the correct discriminator value
  257.                     if (isset($cacheKeyInfo['discriminatorColumn'], $data[$cacheKeyInfo['discriminatorColumn']])
  258.                         && ! in_array((string) $data[$cacheKeyInfo['discriminatorColumn']], $cacheKeyInfo['discriminatorValues'], true)
  259.                     ) {
  260.                         break;
  261.                     }
  262.                     // in an inheritance hierarchy the same field could be defined several times.
  263.                     // We overwrite this value so long we don't have a non-null value, that value we keep.
  264.                     // Per definition it cannot be that a field is defined several times and has several values.
  265.                     if (isset($rowData['data'][$dqlAlias][$fieldName])) {
  266.                         break;
  267.                     }
  268.                     $rowData['data'][$dqlAlias][$fieldName] = $type
  269.                         $type->convertToPHPValue($value$this->_platform)
  270.                         : $value;
  271.                     if ($cacheKeyInfo['isIdentifier'] && $value !== null) {
  272.                         $id[$dqlAlias] .= '|' $value;
  273.                         $nonemptyComponents[$dqlAlias] = true;
  274.                     }
  275.                     break;
  276.             }
  277.         }
  278.         return $rowData;
  279.     }
  280.     /**
  281.      * Processes a row of the result set.
  282.      *
  283.      * Used for HYDRATE_SCALAR. This is a variant of _gatherRowData() that
  284.      * simply converts column names to field names and properly converts the
  285.      * values according to their types. The resulting row has the same number
  286.      * of elements as before.
  287.      *
  288.      * @param array $data
  289.      *
  290.      * @return array The processed row.
  291.      */
  292.     protected function gatherScalarRowData(&$data)
  293.     {
  294.         $rowData = [];
  295.         foreach ($data as $key => $value) {
  296.             if (($cacheKeyInfo $this->hydrateColumnInfo($key)) === null) {
  297.                 continue;
  298.             }
  299.             $fieldName $cacheKeyInfo['fieldName'];
  300.             // WARNING: BC break! We know this is the desired behavior to type convert values, but this
  301.             // erroneous behavior exists since 2.0 and we're forced to keep compatibility.
  302.             if ( ! isset($cacheKeyInfo['isScalar'])) {
  303.                 $dqlAlias  $cacheKeyInfo['dqlAlias'];
  304.                 $type      $cacheKeyInfo['type'];
  305.                 $fieldName $dqlAlias '_' $fieldName;
  306.                 $value     $type
  307.                     $type->convertToPHPValue($value$this->_platform)
  308.                     : $value;
  309.             }
  310.             $rowData[$fieldName] = $value;
  311.         }
  312.         return $rowData;
  313.     }
  314.     /**
  315.      * Retrieve column information from ResultSetMapping.
  316.      *
  317.      * @param string $key Column name
  318.      *
  319.      * @return array|null
  320.      */
  321.     protected function hydrateColumnInfo($key)
  322.     {
  323.         if (isset($this->_cache[$key])) {
  324.             return $this->_cache[$key];
  325.         }
  326.         switch (true) {
  327.             // NOTE: Most of the times it's a field mapping, so keep it first!!!
  328.             case (isset($this->_rsm->fieldMappings[$key])):
  329.                 $classMetadata $this->getClassMetadata($this->_rsm->declaringClasses[$key]);
  330.                 $fieldName     $this->_rsm->fieldMappings[$key];
  331.                 $fieldMapping  $classMetadata->fieldMappings[$fieldName];
  332.                 $ownerMap      $this->_rsm->columnOwnerMap[$key];
  333.                 $columnInfo    = [
  334.                     'isIdentifier' => \in_array($fieldName$classMetadata->identifiertrue),
  335.                     'fieldName'    => $fieldName,
  336.                     'type'         => Type::getType($fieldMapping['type']),
  337.                     'dqlAlias'     => $ownerMap,
  338.                 ];
  339.                 // the current discriminator value must be saved in order to disambiguate fields hydration,
  340.                 // should there be field name collisions
  341.                 if ($classMetadata->parentClasses && isset($this->_rsm->discriminatorColumns[$ownerMap])) {
  342.                     return $this->_cache[$key] = \array_merge(
  343.                         $columnInfo,
  344.                         [
  345.                             'discriminatorColumn' => $this->_rsm->discriminatorColumns[$ownerMap],
  346.                             'discriminatorValue'  => $classMetadata->discriminatorValue,
  347.                             'discriminatorValues' => $this->getDiscriminatorValues($classMetadata),
  348.                         ]
  349.                     );
  350.                 }
  351.                 return $this->_cache[$key] = $columnInfo;
  352.             case (isset($this->_rsm->newObjectMappings[$key])):
  353.                 // WARNING: A NEW object is also a scalar, so it must be declared before!
  354.                 $mapping $this->_rsm->newObjectMappings[$key];
  355.                 return $this->_cache[$key] = [
  356.                     'isScalar'             => true,
  357.                     'isNewObjectParameter' => true,
  358.                     'fieldName'            => $this->_rsm->scalarMappings[$key],
  359.                     'type'                 => Type::getType($this->_rsm->typeMappings[$key]),
  360.                     'argIndex'             => $mapping['argIndex'],
  361.                     'objIndex'             => $mapping['objIndex'],
  362.                     'class'                => new \ReflectionClass($mapping['className']),
  363.                 ];
  364.             case (isset($this->_rsm->scalarMappings[$key])):
  365.                 return $this->_cache[$key] = [
  366.                     'isScalar'  => true,
  367.                     'fieldName' => $this->_rsm->scalarMappings[$key],
  368.                     'type'      => Type::getType($this->_rsm->typeMappings[$key]),
  369.                 ];
  370.             case (isset($this->_rsm->metaMappings[$key])):
  371.                 // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
  372.                 $fieldName $this->_rsm->metaMappings[$key];
  373.                 $dqlAlias  $this->_rsm->columnOwnerMap[$key];
  374.                 $type      = isset($this->_rsm->typeMappings[$key])
  375.                     ? Type::getType($this->_rsm->typeMappings[$key])
  376.                     : null;
  377.                 // Cache metadata fetch
  378.                 $this->getClassMetadata($this->_rsm->aliasMap[$dqlAlias]);
  379.                 return $this->_cache[$key] = [
  380.                     'isIdentifier' => isset($this->_rsm->isIdentifierColumn[$dqlAlias][$key]),
  381.                     'isMetaColumn' => true,
  382.                     'fieldName'    => $fieldName,
  383.                     'type'         => $type,
  384.                     'dqlAlias'     => $dqlAlias,
  385.                 ];
  386.         }
  387.         // this column is a left over, maybe from a LIMIT query hack for example in Oracle or DB2
  388.         // maybe from an additional column that has not been defined in a NativeQuery ResultSetMapping.
  389.         return null;
  390.     }
  391.     /**
  392.      * @return string[]
  393.      */
  394.     private function getDiscriminatorValues(ClassMetadata $classMetadata) : array
  395.     {
  396.         $values array_map(
  397.             function (string $subClass) : string {
  398.                 return (string) $this->getClassMetadata($subClass)->discriminatorValue;
  399.             },
  400.             $classMetadata->subClasses
  401.         );
  402.         $values[] = (string) $classMetadata->discriminatorValue;
  403.         return $values;
  404.     }
  405.     /**
  406.      * Retrieve ClassMetadata associated to entity class name.
  407.      *
  408.      * @param string $className
  409.      *
  410.      * @return \Doctrine\ORM\Mapping\ClassMetadata
  411.      */
  412.     protected function getClassMetadata($className)
  413.     {
  414.         if ( ! isset($this->_metadataCache[$className])) {
  415.             $this->_metadataCache[$className] = $this->_em->getClassMetadata($className);
  416.         }
  417.         return $this->_metadataCache[$className];
  418.     }
  419.     /**
  420.      * Register entity as managed in UnitOfWork.
  421.      *
  422.      * @param ClassMetadata $class
  423.      * @param object        $entity
  424.      * @param array         $data
  425.      *
  426.      * @return void
  427.      *
  428.      * @todo The "$id" generation is the same of UnitOfWork#createEntity. Remove this duplication somehow
  429.      */
  430.     protected function registerManaged(ClassMetadata $class$entity, array $data)
  431.     {
  432.         if ($class->isIdentifierComposite) {
  433.             $id = [];
  434.             foreach ($class->identifier as $fieldName) {
  435.                 $id[$fieldName] = isset($class->associationMappings[$fieldName])
  436.                     ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
  437.                     : $data[$fieldName];
  438.             }
  439.         } else {
  440.             $fieldName $class->identifier[0];
  441.             $id        = [
  442.                 $fieldName => isset($class->associationMappings[$fieldName])
  443.                     ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
  444.                     : $data[$fieldName]
  445.             ];
  446.         }
  447.         $this->_em->getUnitOfWork()->registerManaged($entity$id$data);
  448.     }
  449. }