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

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