vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php line 730

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\Persisters\Entity;
  20. use Doctrine\Common\Collections\Criteria;
  21. use Doctrine\Common\Collections\Expr\Comparison;
  22. use Doctrine\Common\Util\ClassUtils;
  23. use Doctrine\DBAL\Connection;
  24. use Doctrine\DBAL\Driver\ResultStatement as DriverStatement;
  25. use Doctrine\DBAL\LockMode;
  26. use Doctrine\DBAL\Platforms\AbstractPlatform;
  27. use Doctrine\DBAL\Types\Type;
  28. use Doctrine\ORM\EntityManagerInterface;
  29. use Doctrine\ORM\Mapping\ClassMetadata;
  30. use Doctrine\ORM\Mapping\MappingException;
  31. use Doctrine\ORM\Mapping\QuoteStrategy;
  32. use Doctrine\ORM\OptimisticLockException;
  33. use Doctrine\ORM\ORMException;
  34. use Doctrine\ORM\PersistentCollection;
  35. use Doctrine\ORM\Persisters\SqlExpressionVisitor;
  36. use Doctrine\ORM\Persisters\SqlValueVisitor;
  37. use Doctrine\ORM\Query;
  38. use Doctrine\ORM\Query\QueryException;
  39. use Doctrine\ORM\UnitOfWork;
  40. use Doctrine\ORM\Utility\IdentifierFlattener;
  41. use Doctrine\ORM\Utility\PersisterHelper;
  42. use function array_combine;
  43. use function array_map;
  44. use function array_merge;
  45. use function array_search;
  46. use function array_unique;
  47. use function array_values;
  48. use function assert;
  49. use function count;
  50. use function get_class;
  51. use function implode;
  52. use function is_array;
  53. use function is_object;
  54. use function reset;
  55. use function spl_object_hash;
  56. use function sprintf;
  57. use function strpos;
  58. use function strtoupper;
  59. use function trim;
  60. /**
  61.  * A BasicEntityPersister maps an entity to a single table in a relational database.
  62.  *
  63.  * A persister is always responsible for a single entity type.
  64.  *
  65.  * EntityPersisters are used during a UnitOfWork to apply any changes to the persistent
  66.  * state of entities onto a relational database when the UnitOfWork is committed,
  67.  * as well as for basic querying of entities and their associations (not DQL).
  68.  *
  69.  * The persisting operations that are invoked during a commit of a UnitOfWork to
  70.  * persist the persistent entity state are:
  71.  *
  72.  *   - {@link addInsert} : To schedule an entity for insertion.
  73.  *   - {@link executeInserts} : To execute all scheduled insertions.
  74.  *   - {@link update} : To update the persistent state of an entity.
  75.  *   - {@link delete} : To delete the persistent state of an entity.
  76.  *
  77.  * As can be seen from the above list, insertions are batched and executed all at once
  78.  * for increased efficiency.
  79.  *
  80.  * The querying operations invoked during a UnitOfWork, either through direct find
  81.  * requests or lazy-loading, are the following:
  82.  *
  83.  *   - {@link load} : Loads (the state of) a single, managed entity.
  84.  *   - {@link loadAll} : Loads multiple, managed entities.
  85.  *   - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading).
  86.  *   - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading).
  87.  *   - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading).
  88.  *
  89.  * The BasicEntityPersister implementation provides the default behavior for
  90.  * persisting and querying entities that are mapped to a single database table.
  91.  *
  92.  * Subclasses can be created to provide custom persisting and querying strategies,
  93.  * i.e. spanning multiple tables.
  94.  */
  95. class BasicEntityPersister implements EntityPersister
  96. {
  97.     /** @var array<string,string> */
  98.     private static $comparisonMap = [
  99.         Comparison::EQ          => '= %s',
  100.         Comparison::NEQ         => '!= %s',
  101.         Comparison::GT          => '> %s',
  102.         Comparison::GTE         => '>= %s',
  103.         Comparison::LT          => '< %s',
  104.         Comparison::LTE         => '<= %s',
  105.         Comparison::IN          => 'IN (%s)',
  106.         Comparison::NIN         => 'NOT IN (%s)',
  107.         Comparison::CONTAINS    => 'LIKE %s',
  108.         Comparison::STARTS_WITH => 'LIKE %s',
  109.         Comparison::ENDS_WITH   => 'LIKE %s',
  110.     ];
  111.     /**
  112.      * Metadata object that describes the mapping of the mapped entity class.
  113.      *
  114.      * @var ClassMetadata
  115.      */
  116.     protected $class;
  117.     /**
  118.      * The underlying DBAL Connection of the used EntityManager.
  119.      *
  120.      * @var Connection $conn
  121.      */
  122.     protected $conn;
  123.     /**
  124.      * The database platform.
  125.      *
  126.      * @var AbstractPlatform
  127.      */
  128.     protected $platform;
  129.     /**
  130.      * The EntityManager instance.
  131.      *
  132.      * @var EntityManagerInterface
  133.      */
  134.     protected $em;
  135.     /**
  136.      * Queued inserts.
  137.      *
  138.      * @psalm-var array<string, object>
  139.      */
  140.     protected $queuedInserts = [];
  141.     /**
  142.      * The map of column names to DBAL mapping types of all prepared columns used
  143.      * when INSERTing or UPDATEing an entity.
  144.      *
  145.      * @see prepareInsertData($entity)
  146.      * @see prepareUpdateData($entity)
  147.      *
  148.      * @var mixed[]
  149.      */
  150.     protected $columnTypes = [];
  151.     /**
  152.      * The map of quoted column names.
  153.      *
  154.      * @see prepareInsertData($entity)
  155.      * @see prepareUpdateData($entity)
  156.      *
  157.      * @var mixed[]
  158.      */
  159.     protected $quotedColumns = [];
  160.     /**
  161.      * The INSERT SQL statement used for entities handled by this persister.
  162.      * This SQL is only generated once per request, if at all.
  163.      *
  164.      * @var string
  165.      */
  166.     private $insertSql;
  167.     /**
  168.      * The quote strategy.
  169.      *
  170.      * @var QuoteStrategy
  171.      */
  172.     protected $quoteStrategy;
  173.     /**
  174.      * The IdentifierFlattener used for manipulating identifiers
  175.      *
  176.      * @var IdentifierFlattener
  177.      */
  178.     private $identifierFlattener;
  179.     /** @var CachedPersisterContext */
  180.     protected $currentPersisterContext;
  181.     /** @var CachedPersisterContext */
  182.     private $limitsHandlingContext;
  183.     /** @var CachedPersisterContext */
  184.     private $noLimitsContext;
  185.     /**
  186.      * Initializes a new <tt>BasicEntityPersister</tt> that uses the given EntityManager
  187.      * and persists instances of the class described by the given ClassMetadata descriptor.
  188.      */
  189.     public function __construct(EntityManagerInterface $emClassMetadata $class)
  190.     {
  191.         $this->em                    $em;
  192.         $this->class                 $class;
  193.         $this->conn                  $em->getConnection();
  194.         $this->platform              $this->conn->getDatabasePlatform();
  195.         $this->quoteStrategy         $em->getConfiguration()->getQuoteStrategy();
  196.         $this->identifierFlattener   = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory());
  197.         $this->noLimitsContext       $this->currentPersisterContext = new CachedPersisterContext(
  198.             $class,
  199.             new Query\ResultSetMapping(),
  200.             false
  201.         );
  202.         $this->limitsHandlingContext = new CachedPersisterContext(
  203.             $class,
  204.             new Query\ResultSetMapping(),
  205.             true
  206.         );
  207.     }
  208.     /**
  209.      * {@inheritdoc}
  210.      */
  211.     public function getClassMetadata()
  212.     {
  213.         return $this->class;
  214.     }
  215.     /**
  216.      * {@inheritdoc}
  217.      */
  218.     public function getResultSetMapping()
  219.     {
  220.         return $this->currentPersisterContext->rsm;
  221.     }
  222.     /**
  223.      * {@inheritdoc}
  224.      */
  225.     public function addInsert($entity)
  226.     {
  227.         $this->queuedInserts[spl_object_hash($entity)] = $entity;
  228.     }
  229.     /**
  230.      * {@inheritdoc}
  231.      */
  232.     public function getInserts()
  233.     {
  234.         return $this->queuedInserts;
  235.     }
  236.     /**
  237.      * {@inheritdoc}
  238.      */
  239.     public function executeInserts()
  240.     {
  241.         if (! $this->queuedInserts) {
  242.             return [];
  243.         }
  244.         $postInsertIds  = [];
  245.         $idGenerator    $this->class->idGenerator;
  246.         $isPostInsertId $idGenerator->isPostInsertGenerator();
  247.         $stmt      $this->conn->prepare($this->getInsertSQL());
  248.         $tableName $this->class->getTableName();
  249.         foreach ($this->queuedInserts as $entity) {
  250.             $insertData $this->prepareInsertData($entity);
  251.             if (isset($insertData[$tableName])) {
  252.                 $paramIndex 1;
  253.                 foreach ($insertData[$tableName] as $column => $value) {
  254.                     $stmt->bindValue($paramIndex++, $value$this->columnTypes[$column]);
  255.                 }
  256.             }
  257.             $stmt->execute();
  258.             if ($isPostInsertId) {
  259.                 $generatedId     $idGenerator->generate($this->em$entity);
  260.                 $id              = [$this->class->identifier[0] => $generatedId];
  261.                 $postInsertIds[] = [
  262.                     'generatedId' => $generatedId,
  263.                     'entity' => $entity,
  264.                 ];
  265.             } else {
  266.                 $id $this->class->getIdentifierValues($entity);
  267.             }
  268.             if ($this->class->isVersioned) {
  269.                 $this->assignDefaultVersionValue($entity$id);
  270.             }
  271.         }
  272.         $stmt->closeCursor();
  273.         $this->queuedInserts = [];
  274.         return $postInsertIds;
  275.     }
  276.     /**
  277.      * Retrieves the default version value which was created
  278.      * by the preceding INSERT statement and assigns it back in to the
  279.      * entities version field.
  280.      *
  281.      * @param object  $entity
  282.      * @param mixed[] $id
  283.      *
  284.      * @return void
  285.      */
  286.     protected function assignDefaultVersionValue($entity, array $id)
  287.     {
  288.         $value $this->fetchVersionValue($this->class$id);
  289.         $this->class->setFieldValue($entity$this->class->versionField$value);
  290.     }
  291.     /**
  292.      * Fetches the current version value of a versioned entity.
  293.      *
  294.      * @param ClassMetadata $versionedClass
  295.      * @param mixed[]       $id
  296.      *
  297.      * @return mixed
  298.      */
  299.     protected function fetchVersionValue($versionedClass, array $id)
  300.     {
  301.         $versionField $versionedClass->versionField;
  302.         $fieldMapping $versionedClass->fieldMappings[$versionField];
  303.         $tableName    $this->quoteStrategy->getTableName($versionedClass$this->platform);
  304.         $identifier   $this->quoteStrategy->getIdentifierColumnNames($versionedClass$this->platform);
  305.         $columnName   $this->quoteStrategy->getColumnName($versionField$versionedClass$this->platform);
  306.         // FIXME: Order with composite keys might not be correct
  307.         $sql 'SELECT ' $columnName
  308.              ' FROM ' $tableName
  309.              ' WHERE ' implode(' = ? AND '$identifier) . ' = ?';
  310.         $flatId $this->identifierFlattener->flattenIdentifier($versionedClass$id);
  311.         $value $this->conn->fetchColumn(
  312.             $sql,
  313.             array_values($flatId),
  314.             0,
  315.             $this->extractIdentifierTypes($id$versionedClass)
  316.         );
  317.         return Type::getType($fieldMapping['type'])->convertToPHPValue($value$this->platform);
  318.     }
  319.     /**
  320.      * @param mixed[] $id
  321.      *
  322.      * @return int[]|null[]|string[]
  323.      * @psalm-return list<int|string|null>
  324.      */
  325.     private function extractIdentifierTypes(array $idClassMetadata $versionedClass): array
  326.     {
  327.         $types = [];
  328.         foreach ($id as $field => $value) {
  329.             $types array_merge($types$this->getTypes($field$value$versionedClass));
  330.         }
  331.         return $types;
  332.     }
  333.     /**
  334.      * {@inheritdoc}
  335.      */
  336.     public function update($entity)
  337.     {
  338.         $tableName  $this->class->getTableName();
  339.         $updateData $this->prepareUpdateData($entity);
  340.         if (! isset($updateData[$tableName])) {
  341.             return;
  342.         }
  343.         $data $updateData[$tableName];
  344.         if (! $data) {
  345.             return;
  346.         }
  347.         $isVersioned     $this->class->isVersioned;
  348.         $quotedTableName $this->quoteStrategy->getTableName($this->class$this->platform);
  349.         $this->updateTable($entity$quotedTableName$data$isVersioned);
  350.         if ($isVersioned) {
  351.             $id $this->class->getIdentifierValues($entity);
  352.             $this->assignDefaultVersionValue($entity$id);
  353.         }
  354.     }
  355.     /**
  356.      * Performs an UPDATE statement for an entity on a specific table.
  357.      * The UPDATE can optionally be versioned, which requires the entity to have a version field.
  358.      *
  359.      * @param object  $entity          The entity object being updated.
  360.      * @param string  $quotedTableName The quoted name of the table to apply the UPDATE on.
  361.      * @param mixed[] $updateData      The map of columns to update (column => value).
  362.      * @param bool    $versioned       Whether the UPDATE should be versioned.
  363.      *
  364.      * @throws ORMException
  365.      * @throws OptimisticLockException
  366.      */
  367.     final protected function updateTable(
  368.         $entity,
  369.         $quotedTableName,
  370.         array $updateData,
  371.         $versioned false
  372.     ): void {
  373.         $set    = [];
  374.         $types  = [];
  375.         $params = [];
  376.         foreach ($updateData as $columnName => $value) {
  377.             $placeholder '?';
  378.             $column      $columnName;
  379.             switch (true) {
  380.                 case isset($this->class->fieldNames[$columnName]):
  381.                     $fieldName $this->class->fieldNames[$columnName];
  382.                     $column    $this->quoteStrategy->getColumnName($fieldName$this->class$this->platform);
  383.                     if (isset($this->class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  384.                         $type        Type::getType($this->columnTypes[$columnName]);
  385.                         $placeholder $type->convertToDatabaseValueSQL('?'$this->platform);
  386.                     }
  387.                     break;
  388.                 case isset($this->quotedColumns[$columnName]):
  389.                     $column $this->quotedColumns[$columnName];
  390.                     break;
  391.             }
  392.             $params[] = $value;
  393.             $set[]    = $column ' = ' $placeholder;
  394.             $types[]  = $this->columnTypes[$columnName];
  395.         }
  396.         $where      = [];
  397.         $identifier $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  398.         foreach ($this->class->identifier as $idField) {
  399.             if (! isset($this->class->associationMappings[$idField])) {
  400.                 $params[] = $identifier[$idField];
  401.                 $types[]  = $this->class->fieldMappings[$idField]['type'];
  402.                 $where[]  = $this->quoteStrategy->getColumnName($idField$this->class$this->platform);
  403.                 continue;
  404.             }
  405.             $params[] = $identifier[$idField];
  406.             $where[]  = $this->quoteStrategy->getJoinColumnName(
  407.                 $this->class->associationMappings[$idField]['joinColumns'][0],
  408.                 $this->class,
  409.                 $this->platform
  410.             );
  411.             $targetMapping $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']);
  412.             $targetType    PersisterHelper::getTypeOfField($targetMapping->identifier[0], $targetMapping$this->em);
  413.             if ($targetType === []) {
  414.                 throw ORMException::unrecognizedField($targetMapping->identifier[0]);
  415.             }
  416.             $types[] = reset($targetType);
  417.         }
  418.         if ($versioned) {
  419.             $versionField     $this->class->versionField;
  420.             $versionFieldType $this->class->fieldMappings[$versionField]['type'];
  421.             $versionColumn    $this->quoteStrategy->getColumnName($versionField$this->class$this->platform);
  422.             $where[]  = $versionColumn;
  423.             $types[]  = $this->class->fieldMappings[$versionField]['type'];
  424.             $params[] = $this->class->reflFields[$versionField]->getValue($entity);
  425.             switch ($versionFieldType) {
  426.                 case Type::SMALLINT:
  427.                 case Type::INTEGER:
  428.                 case Type::BIGINT:
  429.                     $set[] = $versionColumn ' = ' $versionColumn ' + 1';
  430.                     break;
  431.                 case Type::DATETIME:
  432.                     $set[] = $versionColumn ' = CURRENT_TIMESTAMP';
  433.                     break;
  434.             }
  435.         }
  436.         $sql 'UPDATE ' $quotedTableName
  437.              ' SET ' implode(', '$set)
  438.              . ' WHERE ' implode(' = ? AND '$where) . ' = ?';
  439.         $result $this->conn->executeUpdate($sql$params$types);
  440.         if ($versioned && ! $result) {
  441.             throw OptimisticLockException::lockFailed($entity);
  442.         }
  443.     }
  444.     /**
  445.      * @param array<mixed> $identifier
  446.      * @param string[]     $types
  447.      *
  448.      * @todo Add check for platform if it supports foreign keys/cascading.
  449.      */
  450.     protected function deleteJoinTableRecords(array $identifier, array $types): void
  451.     {
  452.         foreach ($this->class->associationMappings as $mapping) {
  453.             if ($mapping['type'] !== ClassMetadata::MANY_TO_MANY) {
  454.                 continue;
  455.             }
  456.             // @Todo this only covers scenarios with no inheritance or of the same level. Is there something
  457.             // like self-referential relationship between different levels of an inheritance hierarchy? I hope not!
  458.             $selfReferential = ($mapping['targetEntity'] === $mapping['sourceEntity']);
  459.             $class           $this->class;
  460.             $association     $mapping;
  461.             $otherColumns    = [];
  462.             $otherKeys       = [];
  463.             $keys            = [];
  464.             if (! $mapping['isOwningSide']) {
  465.                 $class       $this->em->getClassMetadata($mapping['targetEntity']);
  466.                 $association $class->associationMappings[$mapping['mappedBy']];
  467.             }
  468.             $joinColumns $mapping['isOwningSide']
  469.                 ? $association['joinTable']['joinColumns']
  470.                 : $association['joinTable']['inverseJoinColumns'];
  471.             if ($selfReferential) {
  472.                 $otherColumns = ! $mapping['isOwningSide']
  473.                     ? $association['joinTable']['joinColumns']
  474.                     : $association['joinTable']['inverseJoinColumns'];
  475.             }
  476.             foreach ($joinColumns as $joinColumn) {
  477.                 $keys[] = $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  478.             }
  479.             foreach ($otherColumns as $joinColumn) {
  480.                 $otherKeys[] = $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  481.             }
  482.             if (isset($mapping['isOnDeleteCascade'])) {
  483.                 continue;
  484.             }
  485.             $joinTableName $this->quoteStrategy->getJoinTableName($association$this->class$this->platform);
  486.             $this->conn->delete($joinTableNamearray_combine($keys$identifier), $types);
  487.             if ($selfReferential) {
  488.                 $this->conn->delete($joinTableNamearray_combine($otherKeys$identifier), $types);
  489.             }
  490.         }
  491.     }
  492.     /**
  493.      * {@inheritdoc}
  494.      */
  495.     public function delete($entity)
  496.     {
  497.         $class      $this->class;
  498.         $identifier $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  499.         $tableName  $this->quoteStrategy->getTableName($class$this->platform);
  500.         $idColumns  $this->quoteStrategy->getIdentifierColumnNames($class$this->platform);
  501.         $id         array_combine($idColumns$identifier);
  502.         $types      $this->getClassIdentifiersTypes($class);
  503.         $this->deleteJoinTableRecords($identifier$types);
  504.         return (bool) $this->conn->delete($tableName$id$types);
  505.     }
  506.     /**
  507.      * Prepares the changeset of an entity for database insertion (UPDATE).
  508.      *
  509.      * The changeset is obtained from the currently running UnitOfWork.
  510.      *
  511.      * During this preparation the array that is passed as the second parameter is filled with
  512.      * <columnName> => <value> pairs, grouped by table name.
  513.      *
  514.      * Example:
  515.      * <code>
  516.      * array(
  517.      *    'foo_table' => array('column1' => 'value1', 'column2' => 'value2', ...),
  518.      *    'bar_table' => array('columnX' => 'valueX', 'columnY' => 'valueY', ...),
  519.      *    ...
  520.      * )
  521.      * </code>
  522.      *
  523.      * @param object $entity The entity for which to prepare the data.
  524.      *
  525.      * @return mixed[][] The prepared data.
  526.      * @psalm-return array<string, array<array-key, mixed|null>>
  527.      */
  528.     protected function prepareUpdateData($entity)
  529.     {
  530.         $versionField null;
  531.         $result       = [];
  532.         $uow          $this->em->getUnitOfWork();
  533.         $versioned $this->class->isVersioned;
  534.         if ($versioned !== false) {
  535.             $versionField $this->class->versionField;
  536.         }
  537.         foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
  538.             if (isset($versionField) && $versionField === $field) {
  539.                 continue;
  540.             }
  541.             if (isset($this->class->embeddedClasses[$field])) {
  542.                 continue;
  543.             }
  544.             $newVal $change[1];
  545.             if (! isset($this->class->associationMappings[$field])) {
  546.                 $fieldMapping $this->class->fieldMappings[$field];
  547.                 $columnName   $fieldMapping['columnName'];
  548.                 $this->columnTypes[$columnName] = $fieldMapping['type'];
  549.                 $result[$this->getOwningTable($field)][$columnName] = $newVal;
  550.                 continue;
  551.             }
  552.             $assoc $this->class->associationMappings[$field];
  553.             // Only owning side of x-1 associations can have a FK column.
  554.             if (! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) {
  555.                 continue;
  556.             }
  557.             if ($newVal !== null) {
  558.                 $oid spl_object_hash($newVal);
  559.                 if (isset($this->queuedInserts[$oid]) || $uow->isScheduledForInsert($newVal)) {
  560.                     // The associated entity $newVal is not yet persisted, so we must
  561.                     // set $newVal = null, in order to insert a null value and schedule an
  562.                     // extra update on the UnitOfWork.
  563.                     $uow->scheduleExtraUpdate($entity, [$field => [null$newVal]]);
  564.                     $newVal null;
  565.                 }
  566.             }
  567.             $newValId null;
  568.             if ($newVal !== null) {
  569.                 $newValId $uow->getEntityIdentifier($newVal);
  570.             }
  571.             $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  572.             $owningTable $this->getOwningTable($field);
  573.             foreach ($assoc['joinColumns'] as $joinColumn) {
  574.                 $sourceColumn $joinColumn['name'];
  575.                 $targetColumn $joinColumn['referencedColumnName'];
  576.                 $quotedColumn $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  577.                 $this->quotedColumns[$sourceColumn]  = $quotedColumn;
  578.                 $this->columnTypes[$sourceColumn]    = PersisterHelper::getTypeOfColumn($targetColumn$targetClass$this->em);
  579.                 $result[$owningTable][$sourceColumn] = $newValId
  580.                     $newValId[$targetClass->getFieldForColumn($targetColumn)]
  581.                     : null;
  582.             }
  583.         }
  584.         return $result;
  585.     }
  586.     /**
  587.      * Prepares the data changeset of a managed entity for database insertion (initial INSERT).
  588.      * The changeset of the entity is obtained from the currently running UnitOfWork.
  589.      *
  590.      * The default insert data preparation is the same as for updates.
  591.      *
  592.      * @see prepareUpdateData
  593.      *
  594.      * @param object $entity The entity for which to prepare the data.
  595.      *
  596.      * @return mixed[][] The prepared data for the tables to update.
  597.      * @psalm-return array<string, mixed[]>
  598.      */
  599.     protected function prepareInsertData($entity)
  600.     {
  601.         return $this->prepareUpdateData($entity);
  602.     }
  603.     /**
  604.      * {@inheritdoc}
  605.      */
  606.     public function getOwningTable($fieldName)
  607.     {
  608.         return $this->class->getTableName();
  609.     }
  610.     /**
  611.      * {@inheritdoc}
  612.      */
  613.     public function load(array $criteria$entity null$assoc null, array $hints = [], $lockMode null$limit null, ?array $orderBy null)
  614.     {
  615.         $this->switchPersisterContext(null$limit);
  616.         $sql              $this->getSelectSQL($criteria$assoc$lockMode$limitnull$orderBy);
  617.         [$params$types] = $this->expandParameters($criteria);
  618.         $stmt             $this->conn->executeQuery($sql$params$types);
  619.         if ($entity !== null) {
  620.             $hints[Query::HINT_REFRESH]        = true;
  621.             $hints[Query::HINT_REFRESH_ENTITY] = $entity;
  622.         }
  623.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  624.         $entities $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm$hints);
  625.         return $entities $entities[0] : null;
  626.     }
  627.     /**
  628.      * {@inheritdoc}
  629.      */
  630.     public function loadById(array $identifier$entity null)
  631.     {
  632.         return $this->load($identifier$entity);
  633.     }
  634.     /**
  635.      * {@inheritdoc}
  636.      */
  637.     public function loadOneToOneEntity(array $assoc$sourceEntity, array $identifier = [])
  638.     {
  639.         $foundEntity $this->em->getUnitOfWork()->tryGetById($identifier$assoc['targetEntity']);
  640.         if ($foundEntity !== false) {
  641.             return $foundEntity;
  642.         }
  643.         $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  644.         if ($assoc['isOwningSide']) {
  645.             $isInverseSingleValued $assoc['inversedBy'] && ! $targetClass->isCollectionValuedAssociation($assoc['inversedBy']);
  646.             // Mark inverse side as fetched in the hints, otherwise the UoW would
  647.             // try to load it in a separate query (remember: to-one inverse sides can not be lazy).
  648.             $hints = [];
  649.             if ($isInverseSingleValued) {
  650.                 $hints['fetched']['r'][$assoc['inversedBy']] = true;
  651.             }
  652.             $targetEntity $this->load($identifiernull$assoc$hints);
  653.             // Complete bidirectional association, if necessary
  654.             if ($targetEntity !== null && $isInverseSingleValued) {
  655.                 $targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity$sourceEntity);
  656.             }
  657.             return $targetEntity;
  658.         }
  659.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  660.         $owningAssoc $targetClass->getAssociationMapping($assoc['mappedBy']);
  661.         $computedIdentifier = [];
  662.         // TRICKY: since the association is specular source and target are flipped
  663.         foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  664.             if (! isset($sourceClass->fieldNames[$sourceKeyColumn])) {
  665.                 throw MappingException::joinColumnMustPointToMappedField(
  666.                     $sourceClass->name,
  667.                     $sourceKeyColumn
  668.                 );
  669.             }
  670.             $computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] =
  671.                 $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
  672.         }
  673.         $targetEntity $this->load($computedIdentifiernull$assoc);
  674.         if ($targetEntity !== null) {
  675.             $targetClass->setFieldValue($targetEntity$assoc['mappedBy'], $sourceEntity);
  676.         }
  677.         return $targetEntity;
  678.     }
  679.     /**
  680.      * {@inheritdoc}
  681.      */
  682.     public function refresh(array $id$entity$lockMode null)
  683.     {
  684.         $sql              $this->getSelectSQL($idnull$lockMode);
  685.         [$params$types] = $this->expandParameters($id);
  686.         $stmt             $this->conn->executeQuery($sql$params$types);
  687.         $hydrator $this->em->newHydrator(Query::HYDRATE_OBJECT);
  688.         $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]);
  689.     }
  690.     /**
  691.      * {@inheritDoc}
  692.      */
  693.     public function count($criteria = [])
  694.     {
  695.         $sql $this->getCountSQL($criteria);
  696.         [$params$types] = $criteria instanceof Criteria
  697.             $this->expandCriteriaParameters($criteria)
  698.             : $this->expandParameters($criteria);
  699.         return (int) $this->conn->executeQuery($sql$params$types)->fetchColumn();
  700.     }
  701.     /**
  702.      * {@inheritdoc}
  703.      */
  704.     public function loadCriteria(Criteria $criteria)
  705.     {
  706.         $orderBy $criteria->getOrderings();
  707.         $limit   $criteria->getMaxResults();
  708.         $offset  $criteria->getFirstResult();
  709.         $query   $this->getSelectSQL($criterianullnull$limit$offset$orderBy);
  710.         [$params$types] = $this->expandCriteriaParameters($criteria);
  711.         $stmt     $this->conn->executeQuery($query$params$types);
  712.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  713.         return $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  714.     }
  715.     /**
  716.      * {@inheritdoc}
  717.      */
  718.     public function expandCriteriaParameters(Criteria $criteria)
  719.     {
  720.         $expression $criteria->getWhereExpression();
  721.         $sqlParams  = [];
  722.         $sqlTypes   = [];
  723.         if ($expression === null) {
  724.             return [$sqlParams$sqlTypes];
  725.         }
  726.         $valueVisitor = new SqlValueVisitor();
  727.         $valueVisitor->dispatch($expression);
  728.         [$params$types] = $valueVisitor->getParamsAndTypes();
  729.         foreach ($params as $param) {
  730.             $sqlParams array_merge($sqlParams$this->getValues($param));
  731.         }
  732.         foreach ($types as $type) {
  733.             [$field$value] = $type;
  734.             $sqlTypes        array_merge($sqlTypes$this->getTypes($field$value$this->class));
  735.         }
  736.         return [$sqlParams$sqlTypes];
  737.     }
  738.     /**
  739.      * {@inheritdoc}
  740.      */
  741.     public function loadAll(array $criteria = [], ?array $orderBy null$limit null$offset null)
  742.     {
  743.         $this->switchPersisterContext($offset$limit);
  744.         $sql              $this->getSelectSQL($criterianullnull$limit$offset$orderBy);
  745.         [$params$types] = $this->expandParameters($criteria);
  746.         $stmt             $this->conn->executeQuery($sql$params$types);
  747.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  748.         return $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  749.     }
  750.     /**
  751.      * {@inheritdoc}
  752.      */
  753.     public function getManyToManyCollection(array $assoc$sourceEntity$offset null$limit null)
  754.     {
  755.         $this->switchPersisterContext($offset$limit);
  756.         $stmt $this->getManyToManyStatement($assoc$sourceEntity$offset$limit);
  757.         return $this->loadArrayFromStatement($assoc$stmt);
  758.     }
  759.     /**
  760.      * Loads an array of entities from a given DBAL statement.
  761.      *
  762.      * @param mixed[] $assoc
  763.      *
  764.      * @return mixed[]
  765.      */
  766.     private function loadArrayFromStatement(array $assocDriverStatement $stmt): array
  767.     {
  768.         $rsm   $this->currentPersisterContext->rsm;
  769.         $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true];
  770.         if (isset($assoc['indexBy'])) {
  771.             $rsm = clone $this->currentPersisterContext->rsm// this is necessary because the "default rsm" should be changed.
  772.             $rsm->addIndexBy('r'$assoc['indexBy']);
  773.         }
  774.         return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt$rsm$hints);
  775.     }
  776.     /**
  777.      * Hydrates a collection from a given DBAL statement.
  778.      *
  779.      * @param mixed[] $assoc
  780.      *
  781.      * @return mixed[]
  782.      */
  783.     private function loadCollectionFromStatement(
  784.         array $assoc,
  785.         DriverStatement $stmt,
  786.         PersistentCollection $coll
  787.     ): array {
  788.         $rsm   $this->currentPersisterContext->rsm;
  789.         $hints = [
  790.             UnitOfWork::HINT_DEFEREAGERLOAD => true,
  791.             'collection' => $coll,
  792.         ];
  793.         if (isset($assoc['indexBy'])) {
  794.             $rsm = clone $this->currentPersisterContext->rsm// this is necessary because the "default rsm" should be changed.
  795.             $rsm->addIndexBy('r'$assoc['indexBy']);
  796.         }
  797.         return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt$rsm$hints);
  798.     }
  799.     /**
  800.      * {@inheritdoc}
  801.      */
  802.     public function loadManyToManyCollection(array $assoc$sourceEntityPersistentCollection $collection)
  803.     {
  804.         $stmt $this->getManyToManyStatement($assoc$sourceEntity);
  805.         return $this->loadCollectionFromStatement($assoc$stmt$collection);
  806.     }
  807.     /**
  808.      * @param object $sourceEntity
  809.      * @psalm-param array<string, mixed> $assoc
  810.      *
  811.      * @return DriverStatement
  812.      *
  813.      * @throws MappingException
  814.      */
  815.     private function getManyToManyStatement(
  816.         array $assoc,
  817.         $sourceEntity,
  818.         ?int $offset null,
  819.         ?int $limit null
  820.     ) {
  821.         $this->switchPersisterContext($offset$limit);
  822.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  823.         $class       $sourceClass;
  824.         $association $assoc;
  825.         $criteria    = [];
  826.         $parameters  = [];
  827.         if (! $assoc['isOwningSide']) {
  828.             $class       $this->em->getClassMetadata($assoc['targetEntity']);
  829.             $association $class->associationMappings[$assoc['mappedBy']];
  830.         }
  831.         $joinColumns $assoc['isOwningSide']
  832.             ? $association['joinTable']['joinColumns']
  833.             : $association['joinTable']['inverseJoinColumns'];
  834.         $quotedJoinTable $this->quoteStrategy->getJoinTableName($association$class$this->platform);
  835.         foreach ($joinColumns as $joinColumn) {
  836.             $sourceKeyColumn $joinColumn['referencedColumnName'];
  837.             $quotedKeyColumn $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  838.             switch (true) {
  839.                 case $sourceClass->containsForeignIdentifier:
  840.                     $field $sourceClass->getFieldForColumn($sourceKeyColumn);
  841.                     $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  842.                     if (isset($sourceClass->associationMappings[$field])) {
  843.                         $value $this->em->getUnitOfWork()->getEntityIdentifier($value);
  844.                         $value $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  845.                     }
  846.                     break;
  847.                 case isset($sourceClass->fieldNames[$sourceKeyColumn]):
  848.                     $field $sourceClass->fieldNames[$sourceKeyColumn];
  849.                     $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  850.                     break;
  851.                 default:
  852.                     throw MappingException::joinColumnMustPointToMappedField(
  853.                         $sourceClass->name,
  854.                         $sourceKeyColumn
  855.                     );
  856.             }
  857.             $criteria[$quotedJoinTable '.' $quotedKeyColumn] = $value;
  858.             $parameters[]                                        = [
  859.                 'value' => $value,
  860.                 'field' => $field,
  861.                 'class' => $sourceClass,
  862.             ];
  863.         }
  864.         $sql              $this->getSelectSQL($criteria$assocnull$limit$offset);
  865.         [$params$types] = $this->expandToManyParameters($parameters);
  866.         return $this->conn->executeQuery($sql$params$types);
  867.     }
  868.     /**
  869.      * {@inheritdoc}
  870.      */
  871.     public function getSelectSQL($criteria$assoc null$lockMode null$limit null$offset null, ?array $orderBy null)
  872.     {
  873.         $this->switchPersisterContext($offset$limit);
  874.         $lockSql    '';
  875.         $joinSql    '';
  876.         $orderBySql '';
  877.         if ($assoc !== null && $assoc['type'] === ClassMetadata::MANY_TO_MANY) {
  878.             $joinSql $this->getSelectManyToManyJoinSQL($assoc);
  879.         }
  880.         if (isset($assoc['orderBy'])) {
  881.             $orderBy $assoc['orderBy'];
  882.         }
  883.         if ($orderBy) {
  884.             $orderBySql $this->getOrderBySQL($orderBy$this->getSQLTableAlias($this->class->name));
  885.         }
  886.         $conditionSql $criteria instanceof Criteria
  887.             $this->getSelectConditionCriteriaSQL($criteria)
  888.             : $this->getSelectConditionSQL($criteria$assoc);
  889.         switch ($lockMode) {
  890.             case LockMode::PESSIMISTIC_READ:
  891.                 $lockSql ' ' $this->platform->getReadLockSQL();
  892.                 break;
  893.             case LockMode::PESSIMISTIC_WRITE:
  894.                 $lockSql ' ' $this->platform->getWriteLockSQL();
  895.                 break;
  896.         }
  897.         $columnList $this->getSelectColumnsSQL();
  898.         $tableAlias $this->getSQLTableAlias($this->class->name);
  899.         $filterSql  $this->generateFilterConditionSQL($this->class$tableAlias);
  900.         $tableName  $this->quoteStrategy->getTableName($this->class$this->platform);
  901.         if ($filterSql !== '') {
  902.             $conditionSql $conditionSql
  903.                 $conditionSql ' AND ' $filterSql
  904.                 $filterSql;
  905.         }
  906.         $select 'SELECT ' $columnList;
  907.         $from   ' FROM ' $tableName ' ' $tableAlias;
  908.         $join   $this->currentPersisterContext->selectJoinSql $joinSql;
  909.         $where  = ($conditionSql ' WHERE ' $conditionSql '');
  910.         $lock   $this->platform->appendLockHint($from$lockMode);
  911.         $query  $select
  912.             $lock
  913.             $join
  914.             $where
  915.             $orderBySql;
  916.         return $this->platform->modifyLimitQuery($query$limit$offset) . $lockSql;
  917.     }
  918.     /**
  919.      * {@inheritDoc}
  920.      */
  921.     public function getCountSQL($criteria = [])
  922.     {
  923.         $tableName  $this->quoteStrategy->getTableName($this->class$this->platform);
  924.         $tableAlias $this->getSQLTableAlias($this->class->name);
  925.         $conditionSql $criteria instanceof Criteria
  926.             $this->getSelectConditionCriteriaSQL($criteria)
  927.             : $this->getSelectConditionSQL($criteria);
  928.         $filterSql $this->generateFilterConditionSQL($this->class$tableAlias);
  929.         if ($filterSql !== '') {
  930.             $conditionSql $conditionSql
  931.                 $conditionSql ' AND ' $filterSql
  932.                 $filterSql;
  933.         }
  934.         return 'SELECT COUNT(*) '
  935.             'FROM ' $tableName ' ' $tableAlias
  936.             . (empty($conditionSql) ? '' ' WHERE ' $conditionSql);
  937.     }
  938.     /**
  939.      * Gets the ORDER BY SQL snippet for ordered collections.
  940.      *
  941.      * @psalm-param array<string, string> $orderBy
  942.      *
  943.      * @throws ORMException
  944.      */
  945.     final protected function getOrderBySQL(array $orderBystring $baseTableAlias): string
  946.     {
  947.         $orderByList = [];
  948.         foreach ($orderBy as $fieldName => $orientation) {
  949.             $orientation strtoupper(trim($orientation));
  950.             if ($orientation !== 'ASC' && $orientation !== 'DESC') {
  951.                 throw ORMException::invalidOrientation($this->class->name$fieldName);
  952.             }
  953.             if (isset($this->class->fieldMappings[$fieldName])) {
  954.                 $tableAlias = isset($this->class->fieldMappings[$fieldName]['inherited'])
  955.                     ? $this->getSQLTableAlias($this->class->fieldMappings[$fieldName]['inherited'])
  956.                     : $baseTableAlias;
  957.                 $columnName    $this->quoteStrategy->getColumnName($fieldName$this->class$this->platform);
  958.                 $orderByList[] = $tableAlias '.' $columnName ' ' $orientation;
  959.                 continue;
  960.             }
  961.             if (isset($this->class->associationMappings[$fieldName])) {
  962.                 if (! $this->class->associationMappings[$fieldName]['isOwningSide']) {
  963.                     throw ORMException::invalidFindByInverseAssociation($this->class->name$fieldName);
  964.                 }
  965.                 $tableAlias = isset($this->class->associationMappings[$fieldName]['inherited'])
  966.                     ? $this->getSQLTableAlias($this->class->associationMappings[$fieldName]['inherited'])
  967.                     : $baseTableAlias;
  968.                 foreach ($this->class->associationMappings[$fieldName]['joinColumns'] as $joinColumn) {
  969.                     $columnName    $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  970.                     $orderByList[] = $tableAlias '.' $columnName ' ' $orientation;
  971.                 }
  972.                 continue;
  973.             }
  974.             throw ORMException::unrecognizedField($fieldName);
  975.         }
  976.         return ' ORDER BY ' implode(', '$orderByList);
  977.     }
  978.     /**
  979.      * Gets the SQL fragment with the list of columns to select when querying for
  980.      * an entity in this persister.
  981.      *
  982.      * Subclasses should override this method to alter or change the select column
  983.      * list SQL fragment. Note that in the implementation of BasicEntityPersister
  984.      * the resulting SQL fragment is generated only once and cached in {@link selectColumnListSql}.
  985.      * Subclasses may or may not do the same.
  986.      *
  987.      * @return string The SQL fragment.
  988.      */
  989.     protected function getSelectColumnsSQL()
  990.     {
  991.         if ($this->currentPersisterContext->selectColumnListSql !== null) {
  992.             return $this->currentPersisterContext->selectColumnListSql;
  993.         }
  994.         $columnList = [];
  995.         $this->currentPersisterContext->rsm->addEntityResult($this->class->name'r'); // r for root
  996.         // Add regular columns to select list
  997.         foreach ($this->class->fieldNames as $field) {
  998.             $columnList[] = $this->getSelectColumnSQL($field$this->class);
  999.         }
  1000.         $this->currentPersisterContext->selectJoinSql '';
  1001.         $eagerAliasCounter                            0;
  1002.         foreach ($this->class->associationMappings as $assocField => $assoc) {
  1003.             $assocColumnSQL $this->getSelectColumnAssociationSQL($assocField$assoc$this->class);
  1004.             if ($assocColumnSQL) {
  1005.                 $columnList[] = $assocColumnSQL;
  1006.             }
  1007.             $isAssocToOneInverseSide $assoc['type'] & ClassMetadata::TO_ONE && ! $assoc['isOwningSide'];
  1008.             $isAssocFromOneEager     $assoc['type'] !== ClassMetadata::MANY_TO_MANY && $assoc['fetch'] === ClassMetadata::FETCH_EAGER;
  1009.             if (! ($isAssocFromOneEager || $isAssocToOneInverseSide)) {
  1010.                 continue;
  1011.             }
  1012.             if ((($assoc['type'] & ClassMetadata::TO_MANY) > 0) && $this->currentPersisterContext->handlesLimits) {
  1013.                 continue;
  1014.             }
  1015.             $eagerEntity $this->em->getClassMetadata($assoc['targetEntity']);
  1016.             if ($eagerEntity->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) {
  1017.                 continue; // now this is why you shouldn't use inheritance
  1018.             }
  1019.             $assocAlias 'e' . ($eagerAliasCounter++);
  1020.             $this->currentPersisterContext->rsm->addJoinedEntityResult($assoc['targetEntity'], $assocAlias'r'$assocField);
  1021.             foreach ($eagerEntity->fieldNames as $field) {
  1022.                 $columnList[] = $this->getSelectColumnSQL($field$eagerEntity$assocAlias);
  1023.             }
  1024.             foreach ($eagerEntity->associationMappings as $eagerAssocField => $eagerAssoc) {
  1025.                 $eagerAssocColumnSQL $this->getSelectColumnAssociationSQL(
  1026.                     $eagerAssocField,
  1027.                     $eagerAssoc,
  1028.                     $eagerEntity,
  1029.                     $assocAlias
  1030.                 );
  1031.                 if ($eagerAssocColumnSQL) {
  1032.                     $columnList[] = $eagerAssocColumnSQL;
  1033.                 }
  1034.             }
  1035.             $association   $assoc;
  1036.             $joinCondition = [];
  1037.             if (isset($assoc['indexBy'])) {
  1038.                 $this->currentPersisterContext->rsm->addIndexBy($assocAlias$assoc['indexBy']);
  1039.             }
  1040.             if (! $assoc['isOwningSide']) {
  1041.                 $eagerEntity $this->em->getClassMetadata($assoc['targetEntity']);
  1042.                 $association $eagerEntity->getAssociationMapping($assoc['mappedBy']);
  1043.             }
  1044.             $joinTableAlias $this->getSQLTableAlias($eagerEntity->name$assocAlias);
  1045.             $joinTableName  $this->quoteStrategy->getTableName($eagerEntity$this->platform);
  1046.             if ($assoc['isOwningSide']) {
  1047.                 $tableAlias                                    $this->getSQLTableAlias($association['targetEntity'], $assocAlias);
  1048.                 $this->currentPersisterContext->selectJoinSql .= ' ' $this->getJoinSQLForJoinColumns($association['joinColumns']);
  1049.                 foreach ($association['joinColumns'] as $joinColumn) {
  1050.                     $sourceCol       $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1051.                     $targetCol       $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1052.                     $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'])
  1053.                                         . '.' $sourceCol ' = ' $tableAlias '.' $targetCol;
  1054.                 }
  1055.                 // Add filter SQL
  1056.                 $filterSql $this->generateFilterConditionSQL($eagerEntity$tableAlias);
  1057.                 if ($filterSql) {
  1058.                     $joinCondition[] = $filterSql;
  1059.                 }
  1060.             } else {
  1061.                 $this->currentPersisterContext->selectJoinSql .= ' LEFT JOIN';
  1062.                 foreach ($association['joinColumns'] as $joinColumn) {
  1063.                     $sourceCol $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1064.                     $targetCol $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1065.                     $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'], $assocAlias) . '.' $sourceCol ' = '
  1066.                         $this->getSQLTableAlias($association['targetEntity']) . '.' $targetCol;
  1067.                 }
  1068.             }
  1069.             $this->currentPersisterContext->selectJoinSql .= ' ' $joinTableName ' ' $joinTableAlias ' ON ';
  1070.             $this->currentPersisterContext->selectJoinSql .= implode(' AND '$joinCondition);
  1071.         }
  1072.         $this->currentPersisterContext->selectColumnListSql implode(', '$columnList);
  1073.         return $this->currentPersisterContext->selectColumnListSql;
  1074.     }
  1075.     /**
  1076.      * Gets the SQL join fragment used when selecting entities from an association.
  1077.      *
  1078.      * @param string  $field
  1079.      * @param mixed[] $assoc
  1080.      * @param string  $alias
  1081.      *
  1082.      * @return string
  1083.      */
  1084.     protected function getSelectColumnAssociationSQL($field$assocClassMetadata $class$alias 'r')
  1085.     {
  1086.         if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1087.             return '';
  1088.         }
  1089.         $columnList    = [];
  1090.         $targetClass   $this->em->getClassMetadata($assoc['targetEntity']);
  1091.         $isIdentifier  = isset($assoc['id']) && $assoc['id'] === true;
  1092.         $sqlTableAlias $this->getSQLTableAlias($class->name, ($alias === 'r' '' $alias));
  1093.         foreach ($assoc['joinColumns'] as $joinColumn) {
  1094.             $quotedColumn     $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1095.             $resultColumnName $this->getSQLColumnAlias($joinColumn['name']);
  1096.             $type             PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass$this->em);
  1097.             $this->currentPersisterContext->rsm->addMetaResult($alias$resultColumnName$joinColumn['name'], $isIdentifier$type);
  1098.             $columnList[] = sprintf('%s.%s AS %s'$sqlTableAlias$quotedColumn$resultColumnName);
  1099.         }
  1100.         return implode(', '$columnList);
  1101.     }
  1102.     /**
  1103.      * Gets the SQL join fragment used when selecting entities from a
  1104.      * many-to-many association.
  1105.      *
  1106.      * @psalm-param array<string, mixed> $manyToMany
  1107.      *
  1108.      * @return string
  1109.      */
  1110.     protected function getSelectManyToManyJoinSQL(array $manyToMany)
  1111.     {
  1112.         $conditions       = [];
  1113.         $association      $manyToMany;
  1114.         $sourceTableAlias $this->getSQLTableAlias($this->class->name);
  1115.         if (! $manyToMany['isOwningSide']) {
  1116.             $targetEntity $this->em->getClassMetadata($manyToMany['targetEntity']);
  1117.             $association  $targetEntity->associationMappings[$manyToMany['mappedBy']];
  1118.         }
  1119.         $joinTableName $this->quoteStrategy->getJoinTableName($association$this->class$this->platform);
  1120.         $joinColumns   $manyToMany['isOwningSide']
  1121.             ? $association['joinTable']['inverseJoinColumns']
  1122.             : $association['joinTable']['joinColumns'];
  1123.         foreach ($joinColumns as $joinColumn) {
  1124.             $quotedSourceColumn $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1125.             $quotedTargetColumn $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1126.             $conditions[]       = $sourceTableAlias '.' $quotedTargetColumn ' = ' $joinTableName '.' $quotedSourceColumn;
  1127.         }
  1128.         return ' INNER JOIN ' $joinTableName ' ON ' implode(' AND '$conditions);
  1129.     }
  1130.     /**
  1131.      * {@inheritdoc}
  1132.      */
  1133.     public function getInsertSQL()
  1134.     {
  1135.         if ($this->insertSql !== null) {
  1136.             return $this->insertSql;
  1137.         }
  1138.         $columns   $this->getInsertColumnList();
  1139.         $tableName $this->quoteStrategy->getTableName($this->class$this->platform);
  1140.         if (empty($columns)) {
  1141.             $identityColumn  $this->quoteStrategy->getColumnName($this->class->identifier[0], $this->class$this->platform);
  1142.             $this->insertSql $this->platform->getEmptyIdentityInsertSQL($tableName$identityColumn);
  1143.             return $this->insertSql;
  1144.         }
  1145.         $values  = [];
  1146.         $columns array_unique($columns);
  1147.         foreach ($columns as $column) {
  1148.             $placeholder '?';
  1149.             if (
  1150.                 isset($this->class->fieldNames[$column])
  1151.                 && isset($this->columnTypes[$this->class->fieldNames[$column]])
  1152.                 && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion'])
  1153.             ) {
  1154.                 $type        Type::getType($this->columnTypes[$this->class->fieldNames[$column]]);
  1155.                 $placeholder $type->convertToDatabaseValueSQL('?'$this->platform);
  1156.             }
  1157.             $values[] = $placeholder;
  1158.         }
  1159.         $columns implode(', '$columns);
  1160.         $values  implode(', '$values);
  1161.         $this->insertSql sprintf('INSERT INTO %s (%s) VALUES (%s)'$tableName$columns$values);
  1162.         return $this->insertSql;
  1163.     }
  1164.     /**
  1165.      * Gets the list of columns to put in the INSERT SQL statement.
  1166.      *
  1167.      * Subclasses should override this method to alter or change the list of
  1168.      * columns placed in the INSERT statements used by the persister.
  1169.      *
  1170.      * @return string[] The list of columns.
  1171.      * @psalm-return list<string>
  1172.      */
  1173.     protected function getInsertColumnList()
  1174.     {
  1175.         $columns = [];
  1176.         foreach ($this->class->reflFields as $name => $field) {
  1177.             if ($this->class->isVersioned && $this->class->versionField === $name) {
  1178.                 continue;
  1179.             }
  1180.             if (isset($this->class->embeddedClasses[$name])) {
  1181.                 continue;
  1182.             }
  1183.             if (isset($this->class->associationMappings[$name])) {
  1184.                 $assoc $this->class->associationMappings[$name];
  1185.                 if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  1186.                     foreach ($assoc['joinColumns'] as $joinColumn) {
  1187.                         $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1188.                     }
  1189.                 }
  1190.                 continue;
  1191.             }
  1192.             if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] !== $name) {
  1193.                 $columns[]                = $this->quoteStrategy->getColumnName($name$this->class$this->platform);
  1194.                 $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type'];
  1195.             }
  1196.         }
  1197.         return $columns;
  1198.     }
  1199.     /**
  1200.      * Gets the SQL snippet of a qualified column name for the given field name.
  1201.      *
  1202.      * @param string        $field The field name.
  1203.      * @param ClassMetadata $class The class that declares this field. The table this class is
  1204.      *                             mapped to must own the column for the given field.
  1205.      * @param string        $alias
  1206.      *
  1207.      * @return string
  1208.      */
  1209.     protected function getSelectColumnSQL($fieldClassMetadata $class$alias 'r')
  1210.     {
  1211.         $root         $alias === 'r' '' $alias;
  1212.         $tableAlias   $this->getSQLTableAlias($class->name$root);
  1213.         $fieldMapping $class->fieldMappings[$field];
  1214.         $sql          sprintf('%s.%s'$tableAlias$this->quoteStrategy->getColumnName($field$class$this->platform));
  1215.         $columnAlias  $this->getSQLColumnAlias($fieldMapping['columnName']);
  1216.         $this->currentPersisterContext->rsm->addFieldResult($alias$columnAlias$field);
  1217.         if (isset($fieldMapping['requireSQLConversion'])) {
  1218.             $type Type::getType($fieldMapping['type']);
  1219.             $sql  $type->convertToPHPValueSQL($sql$this->platform);
  1220.         }
  1221.         return $sql ' AS ' $columnAlias;
  1222.     }
  1223.     /**
  1224.      * Gets the SQL table alias for the given class name.
  1225.      *
  1226.      * @param string $className
  1227.      * @param string $assocName
  1228.      *
  1229.      * @return string The SQL table alias.
  1230.      *
  1231.      * @todo Reconsider. Binding table aliases to class names is not such a good idea.
  1232.      */
  1233.     protected function getSQLTableAlias($className$assocName '')
  1234.     {
  1235.         if ($assocName) {
  1236.             $className .= '#' $assocName;
  1237.         }
  1238.         if (isset($this->currentPersisterContext->sqlTableAliases[$className])) {
  1239.             return $this->currentPersisterContext->sqlTableAliases[$className];
  1240.         }
  1241.         $tableAlias 't' $this->currentPersisterContext->sqlAliasCounter++;
  1242.         $this->currentPersisterContext->sqlTableAliases[$className] = $tableAlias;
  1243.         return $tableAlias;
  1244.     }
  1245.     /**
  1246.      * {@inheritdoc}
  1247.      */
  1248.     public function lock(array $criteria$lockMode)
  1249.     {
  1250.         $lockSql      '';
  1251.         $conditionSql $this->getSelectConditionSQL($criteria);
  1252.         switch ($lockMode) {
  1253.             case LockMode::PESSIMISTIC_READ:
  1254.                 $lockSql $this->platform->getReadLockSQL();
  1255.                 break;
  1256.             case LockMode::PESSIMISTIC_WRITE:
  1257.                 $lockSql $this->platform->getWriteLockSQL();
  1258.                 break;
  1259.         }
  1260.         $lock  $this->getLockTablesSql($lockMode);
  1261.         $where = ($conditionSql ' WHERE ' $conditionSql '') . ' ';
  1262.         $sql   'SELECT 1 '
  1263.              $lock
  1264.              $where
  1265.              $lockSql;
  1266.         [$params$types] = $this->expandParameters($criteria);
  1267.         $this->conn->executeQuery($sql$params$types);
  1268.     }
  1269.     /**
  1270.      * Gets the FROM and optionally JOIN conditions to lock the entity managed by this persister.
  1271.      *
  1272.      * @param int|null $lockMode One of the Doctrine\DBAL\LockMode::* constants.
  1273.      *
  1274.      * @return string
  1275.      */
  1276.     protected function getLockTablesSql($lockMode)
  1277.     {
  1278.         return $this->platform->appendLockHint(
  1279.             'FROM '
  1280.             $this->quoteStrategy->getTableName($this->class$this->platform) . ' '
  1281.             $this->getSQLTableAlias($this->class->name),
  1282.             $lockMode
  1283.         );
  1284.     }
  1285.     /**
  1286.      * Gets the Select Where Condition from a Criteria object.
  1287.      *
  1288.      * @return string
  1289.      */
  1290.     protected function getSelectConditionCriteriaSQL(Criteria $criteria)
  1291.     {
  1292.         $expression $criteria->getWhereExpression();
  1293.         if ($expression === null) {
  1294.             return '';
  1295.         }
  1296.         $visitor = new SqlExpressionVisitor($this$this->class);
  1297.         return $visitor->dispatch($expression);
  1298.     }
  1299.     /**
  1300.      * {@inheritdoc}
  1301.      */
  1302.     public function getSelectConditionStatementSQL($field$value$assoc null$comparison null)
  1303.     {
  1304.         $selectedColumns = [];
  1305.         $columns         $this->getSelectConditionStatementColumnSQL($field$assoc);
  1306.         if (count($columns) > && $comparison === Comparison::IN) {
  1307.             /*
  1308.              *  @todo try to support multi-column IN expressions.
  1309.              *  Example: (col1, col2) IN (('val1A', 'val2A'), ('val1B', 'val2B'))
  1310.              */
  1311.             throw ORMException::cantUseInOperatorOnCompositeKeys();
  1312.         }
  1313.         foreach ($columns as $column) {
  1314.             $placeholder '?';
  1315.             if (isset($this->class->fieldMappings[$field]['requireSQLConversion'])) {
  1316.                 $type        Type::getType($this->class->fieldMappings[$field]['type']);
  1317.                 $placeholder $type->convertToDatabaseValueSQL($placeholder$this->platform);
  1318.             }
  1319.             if ($comparison !== null) {
  1320.                 // special case null value handling
  1321.                 if (($comparison === Comparison::EQ || $comparison === Comparison::IS) && $value === null) {
  1322.                     $selectedColumns[] = $column ' IS NULL';
  1323.                     continue;
  1324.                 }
  1325.                 if ($comparison === Comparison::NEQ && $value === null) {
  1326.                     $selectedColumns[] = $column ' IS NOT NULL';
  1327.                     continue;
  1328.                 }
  1329.                 $selectedColumns[] = $column ' ' sprintf(self::$comparisonMap[$comparison], $placeholder);
  1330.                 continue;
  1331.             }
  1332.             if (is_array($value)) {
  1333.                 $in sprintf('%s IN (%s)'$column$placeholder);
  1334.                 if (array_search(null$valuetrue) !== false) {
  1335.                     $selectedColumns[] = sprintf('(%s OR %s IS NULL)'$in$column);
  1336.                     continue;
  1337.                 }
  1338.                 $selectedColumns[] = $in;
  1339.                 continue;
  1340.             }
  1341.             if ($value === null) {
  1342.                 $selectedColumns[] = sprintf('%s IS NULL'$column);
  1343.                 continue;
  1344.             }
  1345.             $selectedColumns[] = sprintf('%s = %s'$column$placeholder);
  1346.         }
  1347.         return implode(' AND '$selectedColumns);
  1348.     }
  1349.     /**
  1350.      * Builds the left-hand-side of a where condition statement.
  1351.      *
  1352.      * @psalm-param array<string, mixed>|null $assoc
  1353.      *
  1354.      * @return string[]
  1355.      * @psalm-return list<string>
  1356.      *
  1357.      * @throws ORMException
  1358.      */
  1359.     private function getSelectConditionStatementColumnSQL(
  1360.         string $field,
  1361.         ?array $assoc null
  1362.     ): array {
  1363.         if (isset($this->class->fieldMappings[$field])) {
  1364.             $className $this->class->fieldMappings[$field]['inherited'] ?? $this->class->name;
  1365.             return [$this->getSQLTableAlias($className) . '.' $this->quoteStrategy->getColumnName($field$this->class$this->platform)];
  1366.         }
  1367.         if (isset($this->class->associationMappings[$field])) {
  1368.             $association $this->class->associationMappings[$field];
  1369.             // Many-To-Many requires join table check for joinColumn
  1370.             $columns = [];
  1371.             $class   $this->class;
  1372.             if ($association['type'] === ClassMetadata::MANY_TO_MANY) {
  1373.                 if (! $association['isOwningSide']) {
  1374.                     $association $assoc;
  1375.                 }
  1376.                 $joinTableName $this->quoteStrategy->getJoinTableName($association$class$this->platform);
  1377.                 $joinColumns   $assoc['isOwningSide']
  1378.                     ? $association['joinTable']['joinColumns']
  1379.                     : $association['joinTable']['inverseJoinColumns'];
  1380.                 foreach ($joinColumns as $joinColumn) {
  1381.                     $columns[] = $joinTableName '.' $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  1382.                 }
  1383.             } else {
  1384.                 if (! $association['isOwningSide']) {
  1385.                     throw ORMException::invalidFindByInverseAssociation($this->class->name$field);
  1386.                 }
  1387.                 $className $association['inherited'] ?? $this->class->name;
  1388.                 foreach ($association['joinColumns'] as $joinColumn) {
  1389.                     $columns[] = $this->getSQLTableAlias($className) . '.' $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1390.                 }
  1391.             }
  1392.             return $columns;
  1393.         }
  1394.         if ($assoc !== null && strpos($field' ') === false && strpos($field'(') === false) {
  1395.             // very careless developers could potentially open up this normally hidden api for userland attacks,
  1396.             // therefore checking for spaces and function calls which are not allowed.
  1397.             // found a join column condition, not really a "field"
  1398.             return [$field];
  1399.         }
  1400.         throw ORMException::unrecognizedField($field);
  1401.     }
  1402.     /**
  1403.      * Gets the conditional SQL fragment used in the WHERE clause when selecting
  1404.      * entities in this persister.
  1405.      *
  1406.      * Subclasses are supposed to override this method if they intend to change
  1407.      * or alter the criteria by which entities are selected.
  1408.      *
  1409.      * @param mixed[]|null $assoc
  1410.      * @psalm-param array<string, mixed> $criteria
  1411.      * @psalm-param array<string, mixed>|null $assoc
  1412.      *
  1413.      * @return string
  1414.      */
  1415.     protected function getSelectConditionSQL(array $criteria$assoc null)
  1416.     {
  1417.         $conditions = [];
  1418.         foreach ($criteria as $field => $value) {
  1419.             $conditions[] = $this->getSelectConditionStatementSQL($field$value$assoc);
  1420.         }
  1421.         return implode(' AND '$conditions);
  1422.     }
  1423.     /**
  1424.      * {@inheritdoc}
  1425.      */
  1426.     public function getOneToManyCollection(array $assoc$sourceEntity$offset null$limit null)
  1427.     {
  1428.         $this->switchPersisterContext($offset$limit);
  1429.         $stmt $this->getOneToManyStatement($assoc$sourceEntity$offset$limit);
  1430.         return $this->loadArrayFromStatement($assoc$stmt);
  1431.     }
  1432.     /**
  1433.      * {@inheritdoc}
  1434.      */
  1435.     public function loadOneToManyCollection(array $assoc$sourceEntityPersistentCollection $collection)
  1436.     {
  1437.         $stmt $this->getOneToManyStatement($assoc$sourceEntity);
  1438.         return $this->loadCollectionFromStatement($assoc$stmt$collection);
  1439.     }
  1440.     /**
  1441.      * Builds criteria and execute SQL statement to fetch the one to many entities from.
  1442.      *
  1443.      * @param object $sourceEntity
  1444.      * @psalm-param array<string, mixed> $assoc
  1445.      */
  1446.     private function getOneToManyStatement(
  1447.         array $assoc,
  1448.         $sourceEntity,
  1449.         ?int $offset null,
  1450.         ?int $limit null
  1451.     ): DriverStatement {
  1452.         $this->switchPersisterContext($offset$limit);
  1453.         $criteria    = [];
  1454.         $parameters  = [];
  1455.         $owningAssoc $this->class->associationMappings[$assoc['mappedBy']];
  1456.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  1457.         $tableAlias  $this->getSQLTableAlias($owningAssoc['inherited'] ?? $this->class->name);
  1458.         foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  1459.             if ($sourceClass->containsForeignIdentifier) {
  1460.                 $field $sourceClass->getFieldForColumn($sourceKeyColumn);
  1461.                 $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1462.                 if (isset($sourceClass->associationMappings[$field])) {
  1463.                     $value $this->em->getUnitOfWork()->getEntityIdentifier($value);
  1464.                     $value $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  1465.                 }
  1466.                 $criteria[$tableAlias '.' $targetKeyColumn] = $value;
  1467.                 $parameters[]                                   = [
  1468.                     'value' => $value,
  1469.                     'field' => $field,
  1470.                     'class' => $sourceClass,
  1471.                 ];
  1472.                 continue;
  1473.             }
  1474.             $field $sourceClass->fieldNames[$sourceKeyColumn];
  1475.             $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1476.             $criteria[$tableAlias '.' $targetKeyColumn] = $value;
  1477.             $parameters[]                                   = [
  1478.                 'value' => $value,
  1479.                 'field' => $field,
  1480.                 'class' => $sourceClass,
  1481.             ];
  1482.         }
  1483.         $sql              $this->getSelectSQL($criteria$assocnull$limit$offset);
  1484.         [$params$types] = $this->expandToManyParameters($parameters);
  1485.         return $this->conn->executeQuery($sql$params$types);
  1486.     }
  1487.     /**
  1488.      * {@inheritdoc}
  1489.      */
  1490.     public function expandParameters($criteria)
  1491.     {
  1492.         $params = [];
  1493.         $types  = [];
  1494.         foreach ($criteria as $field => $value) {
  1495.             if ($value === null) {
  1496.                 continue; // skip null values.
  1497.             }
  1498.             $types  array_merge($types$this->getTypes($field$value$this->class));
  1499.             $params array_merge($params$this->getValues($value));
  1500.         }
  1501.         return [$params$types];
  1502.     }
  1503.     /**
  1504.      * Expands the parameters from the given criteria and use the correct binding types if found,
  1505.      * specialized for OneToMany or ManyToMany associations.
  1506.      *
  1507.      * @param mixed[][] $criteria an array of arrays containing following:
  1508.      *                             - field to which each criterion will be bound
  1509.      *                             - value to be bound
  1510.      *                             - class to which the field belongs to
  1511.      *
  1512.      * @return mixed[][]
  1513.      * @psalm-return array{0: array, 1: list<int|string|null>}
  1514.      */
  1515.     private function expandToManyParameters(array $criteria): array
  1516.     {
  1517.         $params = [];
  1518.         $types  = [];
  1519.         foreach ($criteria as $criterion) {
  1520.             if ($criterion['value'] === null) {
  1521.                 continue; // skip null values.
  1522.             }
  1523.             $types  array_merge($types$this->getTypes($criterion['field'], $criterion['value'], $criterion['class']));
  1524.             $params array_merge($params$this->getValues($criterion['value']));
  1525.         }
  1526.         return [$params$types];
  1527.     }
  1528.     /**
  1529.      * Infers field types to be used by parameter type casting.
  1530.      *
  1531.      * @param mixed $value
  1532.      *
  1533.      * @return int[]|null[]|string[]
  1534.      * @psalm-return list<int|string|null>
  1535.      *
  1536.      * @throws QueryException
  1537.      */
  1538.     private function getTypes(string $field$valueClassMetadata $class): array
  1539.     {
  1540.         $types = [];
  1541.         switch (true) {
  1542.             case isset($class->fieldMappings[$field]):
  1543.                 $types array_merge($types, [$class->fieldMappings[$field]['type']]);
  1544.                 break;
  1545.             case isset($class->associationMappings[$field]):
  1546.                 $assoc $class->associationMappings[$field];
  1547.                 $class $this->em->getClassMetadata($assoc['targetEntity']);
  1548.                 if (! $assoc['isOwningSide']) {
  1549.                     $assoc $class->associationMappings[$assoc['mappedBy']];
  1550.                     $class $this->em->getClassMetadata($assoc['targetEntity']);
  1551.                 }
  1552.                 $columns $assoc['type'] === ClassMetadata::MANY_TO_MANY
  1553.                     $assoc['relationToTargetKeyColumns']
  1554.                     : $assoc['sourceToTargetKeyColumns'];
  1555.                 foreach ($columns as $column) {
  1556.                     $types[] = PersisterHelper::getTypeOfColumn($column$class$this->em);
  1557.                 }
  1558.                 break;
  1559.             default:
  1560.                 $types[] = null;
  1561.                 break;
  1562.         }
  1563.         if (is_array($value)) {
  1564.             return array_map(static function ($type) {
  1565.                 $type Type::getType($type);
  1566.                 return $type->getBindingType() + Connection::ARRAY_PARAM_OFFSET;
  1567.             }, $types);
  1568.         }
  1569.         return $types;
  1570.     }
  1571.     /**
  1572.      * Retrieves the parameters that identifies a value.
  1573.      *
  1574.      * @param mixed $value
  1575.      *
  1576.      * @return mixed[]
  1577.      */
  1578.     private function getValues($value): array
  1579.     {
  1580.         if (is_array($value)) {
  1581.             $newValue = [];
  1582.             foreach ($value as $itemValue) {
  1583.                 $newValue array_merge($newValue$this->getValues($itemValue));
  1584.             }
  1585.             return [$newValue];
  1586.         }
  1587.         if (is_object($value) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) {
  1588.             $class $this->em->getClassMetadata(get_class($value));
  1589.             if ($class->isIdentifierComposite) {
  1590.                 $newValue = [];
  1591.                 foreach ($class->getIdentifierValues($value) as $innerValue) {
  1592.                     $newValue array_merge($newValue$this->getValues($innerValue));
  1593.                 }
  1594.                 return $newValue;
  1595.             }
  1596.         }
  1597.         return [$this->getIndividualValue($value)];
  1598.     }
  1599.     /**
  1600.      * Retrieves an individual parameter value.
  1601.      *
  1602.      * @param mixed $value
  1603.      *
  1604.      * @return mixed
  1605.      */
  1606.     private function getIndividualValue($value)
  1607.     {
  1608.         if (! is_object($value) || ! $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) {
  1609.             return $value;
  1610.         }
  1611.         return $this->em->getUnitOfWork()->getSingleIdentifierValue($value);
  1612.     }
  1613.     /**
  1614.      * {@inheritdoc}
  1615.      */
  1616.     public function exists($entity, ?Criteria $extraConditions null)
  1617.     {
  1618.         $criteria $this->class->getIdentifierValues($entity);
  1619.         if (! $criteria) {
  1620.             return false;
  1621.         }
  1622.         $alias $this->getSQLTableAlias($this->class->name);
  1623.         $sql 'SELECT 1 '
  1624.              $this->getLockTablesSql(null)
  1625.              . ' WHERE ' $this->getSelectConditionSQL($criteria);
  1626.         [$params$types] = $this->expandParameters($criteria);
  1627.         if ($extraConditions !== null) {
  1628.             $sql                             .= ' AND ' $this->getSelectConditionCriteriaSQL($extraConditions);
  1629.             [$criteriaParams$criteriaTypes] = $this->expandCriteriaParameters($extraConditions);
  1630.             $params array_merge($params$criteriaParams);
  1631.             $types  array_merge($types$criteriaTypes);
  1632.         }
  1633.         $filterSql $this->generateFilterConditionSQL($this->class$alias);
  1634.         if ($filterSql) {
  1635.             $sql .= ' AND ' $filterSql;
  1636.         }
  1637.         return (bool) $this->conn->fetchColumn($sql$params0$types);
  1638.     }
  1639.     /**
  1640.      * Generates the appropriate join SQL for the given join column.
  1641.      *
  1642.      * @param array[] $joinColumns The join columns definition of an association.
  1643.      * @psalm-param array<array<string, mixed>> $joinColumns
  1644.      *
  1645.      * @return string LEFT JOIN if one of the columns is nullable, INNER JOIN otherwise.
  1646.      */
  1647.     protected function getJoinSQLForJoinColumns($joinColumns)
  1648.     {
  1649.         // if one of the join columns is nullable, return left join
  1650.         foreach ($joinColumns as $joinColumn) {
  1651.             if (! isset($joinColumn['nullable']) || $joinColumn['nullable']) {
  1652.                 return 'LEFT JOIN';
  1653.             }
  1654.         }
  1655.         return 'INNER JOIN';
  1656.     }
  1657.     /**
  1658.      * @param string $columnName
  1659.      *
  1660.      * @return string
  1661.      */
  1662.     public function getSQLColumnAlias($columnName)
  1663.     {
  1664.         return $this->quoteStrategy->getColumnAlias($columnName$this->currentPersisterContext->sqlAliasCounter++, $this->platform);
  1665.     }
  1666.     /**
  1667.      * Generates the filter SQL for a given entity and table alias.
  1668.      *
  1669.      * @param ClassMetadata $targetEntity     Metadata of the target entity.
  1670.      * @param string        $targetTableAlias The table alias of the joined/selected table.
  1671.      *
  1672.      * @return string The SQL query part to add to a query.
  1673.      */
  1674.     protected function generateFilterConditionSQL(ClassMetadata $targetEntity$targetTableAlias)
  1675.     {
  1676.         $filterClauses = [];
  1677.         foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  1678.             $filterExpr $filter->addFilterConstraint($targetEntity$targetTableAlias);
  1679.             if ($filterExpr !== '') {
  1680.                 $filterClauses[] = '(' $filterExpr ')';
  1681.             }
  1682.         }
  1683.         $sql implode(' AND '$filterClauses);
  1684.         return $sql '(' $sql ')' ''// Wrap again to avoid "X or Y and FilterConditionSQL"
  1685.     }
  1686.     /**
  1687.      * Switches persister context according to current query offset/limits
  1688.      *
  1689.      * This is due to the fact that to-many associations cannot be fetch-joined when a limit is involved
  1690.      *
  1691.      * @param int|null $offset
  1692.      * @param int|null $limit
  1693.      *
  1694.      * @return void
  1695.      */
  1696.     protected function switchPersisterContext($offset$limit)
  1697.     {
  1698.         if ($offset === null && $limit === null) {
  1699.             $this->currentPersisterContext $this->noLimitsContext;
  1700.             return;
  1701.         }
  1702.         $this->currentPersisterContext $this->limitsHandlingContext;
  1703.     }
  1704.     /**
  1705.      * @return string[]
  1706.      * @psalm-return list<string>
  1707.      */
  1708.     protected function getClassIdentifiersTypes(ClassMetadata $class): array
  1709.     {
  1710.         $entityManager $this->em;
  1711.         return array_map(
  1712.             static function ($fieldName) use ($class$entityManager): string {
  1713.                 $types PersisterHelper::getTypeOfField($fieldName$class$entityManager);
  1714.                 assert(isset($types[0]));
  1715.                 return $types[0];
  1716.             },
  1717.             $class->identifier
  1718.         );
  1719.     }
  1720. }