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

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