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

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