vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php line 285

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;
  20. use Doctrine\Common\EventManager;
  21. use Doctrine\DBAL\Connection;
  22. use Doctrine\DBAL\DriverManager;
  23. use Doctrine\DBAL\LockMode;
  24. use Doctrine\ORM\Mapping\ClassMetadata;
  25. use Doctrine\ORM\Query\ResultSetMapping;
  26. use Doctrine\ORM\Proxy\ProxyFactory;
  27. use Doctrine\ORM\Query\FilterCollection;
  28. use Doctrine\Common\Util\ClassUtils;
  29. use Doctrine\Persistence\Mapping\MappingException;
  30. use Doctrine\Persistence\ObjectRepository;
  31. use Throwable;
  32. use const E_USER_DEPRECATED;
  33. use function trigger_error;
  34. /**
  35.  * The EntityManager is the central access point to ORM functionality.
  36.  *
  37.  * It is a facade to all different ORM subsystems such as UnitOfWork,
  38.  * Query Language and Repository API. Instantiation is done through
  39.  * the static create() method. The quickest way to obtain a fully
  40.  * configured EntityManager is:
  41.  *
  42.  *     use Doctrine\ORM\Tools\Setup;
  43.  *     use Doctrine\ORM\EntityManager;
  44.  *
  45.  *     $paths = array('/path/to/entity/mapping/files');
  46.  *
  47.  *     $config = Setup::createAnnotationMetadataConfiguration($paths);
  48.  *     $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true);
  49.  *     $entityManager = EntityManager::create($dbParams, $config);
  50.  *
  51.  * For more information see
  52.  * {@link http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html}
  53.  *
  54.  * You should never attempt to inherit from the EntityManager: Inheritance
  55.  * is not a valid extension point for the EntityManager. Instead you
  56.  * should take a look at the {@see \Doctrine\ORM\Decorator\EntityManagerDecorator}
  57.  * and wrap your entity manager in a decorator.
  58.  *
  59.  * @since   2.0
  60.  * @author  Benjamin Eberlei <kontakt@beberlei.de>
  61.  * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
  62.  * @author  Jonathan Wage <jonwage@gmail.com>
  63.  * @author  Roman Borschel <roman@code-factory.org>
  64.  */
  65. /* final */class EntityManager implements EntityManagerInterface
  66. {
  67.     /**
  68.      * The used Configuration.
  69.      *
  70.      * @var \Doctrine\ORM\Configuration
  71.      */
  72.     private $config;
  73.     /**
  74.      * The database connection used by the EntityManager.
  75.      *
  76.      * @var \Doctrine\DBAL\Connection
  77.      */
  78.     private $conn;
  79.     /**
  80.      * The metadata factory, used to retrieve the ORM metadata of entity classes.
  81.      *
  82.      * @var \Doctrine\ORM\Mapping\ClassMetadataFactory
  83.      */
  84.     private $metadataFactory;
  85.     /**
  86.      * The UnitOfWork used to coordinate object-level transactions.
  87.      *
  88.      * @var \Doctrine\ORM\UnitOfWork
  89.      */
  90.     private $unitOfWork;
  91.     /**
  92.      * The event manager that is the central point of the event system.
  93.      *
  94.      * @var \Doctrine\Common\EventManager
  95.      */
  96.     private $eventManager;
  97.     /**
  98.      * The proxy factory used to create dynamic proxies.
  99.      *
  100.      * @var \Doctrine\ORM\Proxy\ProxyFactory
  101.      */
  102.     private $proxyFactory;
  103.     /**
  104.      * The repository factory used to create dynamic repositories.
  105.      *
  106.      * @var \Doctrine\ORM\Repository\RepositoryFactory
  107.      */
  108.     private $repositoryFactory;
  109.     /**
  110.      * The expression builder instance used to generate query expressions.
  111.      *
  112.      * @var \Doctrine\ORM\Query\Expr
  113.      */
  114.     private $expressionBuilder;
  115.     /**
  116.      * Whether the EntityManager is closed or not.
  117.      *
  118.      * @var bool
  119.      */
  120.     private $closed false;
  121.     /**
  122.      * Collection of query filters.
  123.      *
  124.      * @var \Doctrine\ORM\Query\FilterCollection
  125.      */
  126.     private $filterCollection;
  127.     /**
  128.      * @var \Doctrine\ORM\Cache The second level cache regions API.
  129.      */
  130.     private $cache;
  131.     /**
  132.      * Creates a new EntityManager that operates on the given database connection
  133.      * and uses the given Configuration and EventManager implementations.
  134.      *
  135.      * @param \Doctrine\DBAL\Connection     $conn
  136.      * @param \Doctrine\ORM\Configuration   $config
  137.      * @param \Doctrine\Common\EventManager $eventManager
  138.      */
  139.     protected function __construct(Connection $connConfiguration $configEventManager $eventManager)
  140.     {
  141.         $this->conn              $conn;
  142.         $this->config            $config;
  143.         $this->eventManager      $eventManager;
  144.         $metadataFactoryClassName $config->getClassMetadataFactoryName();
  145.         $this->metadataFactory = new $metadataFactoryClassName;
  146.         $this->metadataFactory->setEntityManager($this);
  147.         $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl());
  148.         $this->repositoryFactory $config->getRepositoryFactory();
  149.         $this->unitOfWork        = new UnitOfWork($this);
  150.         $this->proxyFactory      = new ProxyFactory(
  151.             $this,
  152.             $config->getProxyDir(),
  153.             $config->getProxyNamespace(),
  154.             $config->getAutoGenerateProxyClasses()
  155.         );
  156.         if ($config->isSecondLevelCacheEnabled()) {
  157.             $cacheConfig    $config->getSecondLevelCacheConfiguration();
  158.             $cacheFactory   $cacheConfig->getCacheFactory();
  159.             $this->cache    $cacheFactory->createCache($this);
  160.         }
  161.     }
  162.     /**
  163.      * {@inheritDoc}
  164.      */
  165.     public function getConnection()
  166.     {
  167.         return $this->conn;
  168.     }
  169.     /**
  170.      * Gets the metadata factory used to gather the metadata of classes.
  171.      *
  172.      * @return \Doctrine\ORM\Mapping\ClassMetadataFactory
  173.      */
  174.     public function getMetadataFactory()
  175.     {
  176.         return $this->metadataFactory;
  177.     }
  178.     /**
  179.      * {@inheritDoc}
  180.      */
  181.     public function getExpressionBuilder()
  182.     {
  183.         if ($this->expressionBuilder === null) {
  184.             $this->expressionBuilder = new Query\Expr;
  185.         }
  186.         return $this->expressionBuilder;
  187.     }
  188.     /**
  189.      * {@inheritDoc}
  190.      */
  191.     public function beginTransaction()
  192.     {
  193.         $this->conn->beginTransaction();
  194.     }
  195.     /**
  196.      * {@inheritDoc}
  197.      */
  198.     public function getCache()
  199.     {
  200.         return $this->cache;
  201.     }
  202.     /**
  203.      * {@inheritDoc}
  204.      */
  205.     public function transactional($func)
  206.     {
  207.         if (!is_callable($func)) {
  208.             throw new \InvalidArgumentException('Expected argument of type "callable", got "' gettype($func) . '"');
  209.         }
  210.         $this->conn->beginTransaction();
  211.         try {
  212.             $return call_user_func($func$this);
  213.             $this->flush();
  214.             $this->conn->commit();
  215.             return $return ?: true;
  216.         } catch (Throwable $e) {
  217.             $this->close();
  218.             $this->conn->rollBack();
  219.             throw $e;
  220.         }
  221.     }
  222.     /**
  223.      * {@inheritDoc}
  224.      */
  225.     public function commit()
  226.     {
  227.         $this->conn->commit();
  228.     }
  229.     /**
  230.      * {@inheritDoc}
  231.      */
  232.     public function rollback()
  233.     {
  234.         $this->conn->rollBack();
  235.     }
  236.     /**
  237.      * Returns the ORM metadata descriptor for a class.
  238.      *
  239.      * The class name must be the fully-qualified class name without a leading backslash
  240.      * (as it is returned by get_class($obj)) or an aliased class name.
  241.      *
  242.      * Examples:
  243.      * MyProject\Domain\User
  244.      * sales:PriceRequest
  245.      *
  246.      * Internal note: Performance-sensitive method.
  247.      *
  248.      * @param string $className
  249.      *
  250.      * @return \Doctrine\ORM\Mapping\ClassMetadata
  251.      */
  252.     public function getClassMetadata($className)
  253.     {
  254.         return $this->metadataFactory->getMetadataFor($className);
  255.     }
  256.     /**
  257.      * {@inheritDoc}
  258.      */
  259.     public function createQuery($dql '')
  260.     {
  261.         $query = new Query($this);
  262.         if ( ! empty($dql)) {
  263.             $query->setDQL($dql);
  264.         }
  265.         return $query;
  266.     }
  267.     /**
  268.      * {@inheritDoc}
  269.      */
  270.     public function createNamedQuery($name)
  271.     {
  272.         return $this->createQuery($this->config->getNamedQuery($name));
  273.     }
  274.     /**
  275.      * {@inheritDoc}
  276.      */
  277.     public function createNativeQuery($sqlResultSetMapping $rsm)
  278.     {
  279.         $query = new NativeQuery($this);
  280.         $query->setSQL($sql);
  281.         $query->setResultSetMapping($rsm);
  282.         return $query;
  283.     }
  284.     /**
  285.      * {@inheritDoc}
  286.      */
  287.     public function createNamedNativeQuery($name)
  288.     {
  289.         list($sql$rsm) = $this->config->getNamedNativeQuery($name);
  290.         return $this->createNativeQuery($sql$rsm);
  291.     }
  292.     /**
  293.      * {@inheritDoc}
  294.      */
  295.     public function createQueryBuilder()
  296.     {
  297.         return new QueryBuilder($this);
  298.     }
  299.     /**
  300.      * Flushes all changes to objects that have been queued up to now to the database.
  301.      * This effectively synchronizes the in-memory state of managed objects with the
  302.      * database.
  303.      *
  304.      * If an entity is explicitly passed to this method only this entity and
  305.      * the cascade-persist semantics + scheduled inserts/removals are synchronized.
  306.      *
  307.      * @param null|object|array $entity
  308.      *
  309.      * @return void
  310.      *
  311.      * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
  312.      *         makes use of optimistic locking fails.
  313.      * @throws ORMException
  314.      */
  315.     public function flush($entity null)
  316.     {
  317.         if ($entity !== null) {
  318.             @trigger_error(
  319.                 'Calling ' __METHOD__ '() with any arguments to flush specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
  320.                 E_USER_DEPRECATED
  321.             );
  322.         }
  323.         $this->errorIfClosed();
  324.         $this->unitOfWork->commit($entity);
  325.     }
  326.     /**
  327.      * Finds an Entity by its identifier.
  328.      *
  329.      * @param string       $entityName  The class name of the entity to find.
  330.      * @param mixed        $id          The identity of the entity to find.
  331.      * @param integer|null $lockMode    One of the \Doctrine\DBAL\LockMode::* constants
  332.      *                                  or NULL if no specific lock mode should be used
  333.      *                                  during the search.
  334.      * @param integer|null $lockVersion The version of the entity to find when using
  335.      *                                  optimistic locking.
  336.      *
  337.      * @return object|null The entity instance or NULL if the entity can not be found.
  338.      *
  339.      * @throws OptimisticLockException
  340.      * @throws ORMInvalidArgumentException
  341.      * @throws TransactionRequiredException
  342.      * @throws ORMException
  343.      */
  344.     public function find($entityName$id$lockMode null$lockVersion null)
  345.     {
  346.         $class $this->metadataFactory->getMetadataFor(ltrim($entityName'\\'));
  347.         if ($lockMode !== null) {
  348.             $this->checkLockRequirements($lockMode$class);
  349.         }
  350.         if ( ! is_array($id)) {
  351.             if ($class->isIdentifierComposite) {
  352.                 throw ORMInvalidArgumentException::invalidCompositeIdentifier();
  353.             }
  354.             $id = [$class->identifier[0] => $id];
  355.         }
  356.         foreach ($id as $i => $value) {
  357.             if (is_object($value) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) {
  358.                 $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value);
  359.                 if ($id[$i] === null) {
  360.                     throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
  361.                 }
  362.             }
  363.         }
  364.         $sortedId = [];
  365.         foreach ($class->identifier as $identifier) {
  366.             if ( ! isset($id[$identifier])) {
  367.                 throw ORMException::missingIdentifierField($class->name$identifier);
  368.             }
  369.             $sortedId[$identifier] = $id[$identifier];
  370.             unset($id[$identifier]);
  371.         }
  372.         if ($id) {
  373.             throw ORMException::unrecognizedIdentifierFields($class->namearray_keys($id));
  374.         }
  375.         $unitOfWork $this->getUnitOfWork();
  376.         // Check identity map first
  377.         if (($entity $unitOfWork->tryGetById($sortedId$class->rootEntityName)) !== false) {
  378.             if ( ! ($entity instanceof $class->name)) {
  379.                 return null;
  380.             }
  381.             switch (true) {
  382.                 case LockMode::OPTIMISTIC === $lockMode:
  383.                     $this->lock($entity$lockMode$lockVersion);
  384.                     break;
  385.                 case LockMode::NONE === $lockMode:
  386.                 case LockMode::PESSIMISTIC_READ === $lockMode:
  387.                 case LockMode::PESSIMISTIC_WRITE === $lockMode:
  388.                     $persister $unitOfWork->getEntityPersister($class->name);
  389.                     $persister->refresh($sortedId$entity$lockMode);
  390.                     break;
  391.             }
  392.             return $entity// Hit!
  393.         }
  394.         $persister $unitOfWork->getEntityPersister($class->name);
  395.         switch (true) {
  396.             case LockMode::OPTIMISTIC === $lockMode:
  397.                 $entity $persister->load($sortedId);
  398.                 $unitOfWork->lock($entity$lockMode$lockVersion);
  399.                 return $entity;
  400.             case LockMode::PESSIMISTIC_READ === $lockMode:
  401.             case LockMode::PESSIMISTIC_WRITE === $lockMode:
  402.                 return $persister->load($sortedIdnullnull, [], $lockMode);
  403.             default:
  404.                 return $persister->loadById($sortedId);
  405.         }
  406.     }
  407.     /**
  408.      * {@inheritDoc}
  409.      */
  410.     public function getReference($entityName$id)
  411.     {
  412.         $class $this->metadataFactory->getMetadataFor(ltrim($entityName'\\'));
  413.         if ( ! is_array($id)) {
  414.             $id = [$class->identifier[0] => $id];
  415.         }
  416.         $sortedId = [];
  417.         foreach ($class->identifier as $identifier) {
  418.             if ( ! isset($id[$identifier])) {
  419.                 throw ORMException::missingIdentifierField($class->name$identifier);
  420.             }
  421.             $sortedId[$identifier] = $id[$identifier];
  422.             unset($id[$identifier]);
  423.         }
  424.         if ($id) {
  425.             throw ORMException::unrecognizedIdentifierFields($class->namearray_keys($id));
  426.         }
  427.         // Check identity map first, if its already in there just return it.
  428.         if (($entity $this->unitOfWork->tryGetById($sortedId$class->rootEntityName)) !== false) {
  429.             return ($entity instanceof $class->name) ? $entity null;
  430.         }
  431.         if ($class->subClasses) {
  432.             return $this->find($entityName$sortedId);
  433.         }
  434.         $entity $this->proxyFactory->getProxy($class->name$sortedId);
  435.         $this->unitOfWork->registerManaged($entity$sortedId, []);
  436.         return $entity;
  437.     }
  438.     /**
  439.      * {@inheritDoc}
  440.      */
  441.     public function getPartialReference($entityName$identifier)
  442.     {
  443.         $class $this->metadataFactory->getMetadataFor(ltrim($entityName'\\'));
  444.         // Check identity map first, if its already in there just return it.
  445.         if (($entity $this->unitOfWork->tryGetById($identifier$class->rootEntityName)) !== false) {
  446.             return ($entity instanceof $class->name) ? $entity null;
  447.         }
  448.         if ( ! is_array($identifier)) {
  449.             $identifier = [$class->identifier[0] => $identifier];
  450.         }
  451.         $entity $class->newInstance();
  452.         $class->setIdentifierValues($entity$identifier);
  453.         $this->unitOfWork->registerManaged($entity$identifier, []);
  454.         $this->unitOfWork->markReadOnly($entity);
  455.         return $entity;
  456.     }
  457.     /**
  458.      * Clears the EntityManager. All entities that are currently managed
  459.      * by this EntityManager become detached.
  460.      *
  461.      * @param string|null $entityName if given, only entities of this type will get detached
  462.      *
  463.      * @return void
  464.      *
  465.      * @throws ORMInvalidArgumentException If a non-null non-string value is given.
  466.      * @throws MappingException            If a $entityName is given, but that entity is not
  467.      *                                     found in the mappings.
  468.      */
  469.     public function clear($entityName null)
  470.     {
  471.         if (null !== $entityName && ! is_string($entityName)) {
  472.             throw ORMInvalidArgumentException::invalidEntityName($entityName);
  473.         }
  474.         if ($entityName !== null) {
  475.             @trigger_error(
  476.                 'Calling ' __METHOD__ '() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
  477.                 E_USER_DEPRECATED
  478.             );
  479.         }
  480.         $this->unitOfWork->clear(
  481.             null === $entityName
  482.                 null
  483.                 $this->metadataFactory->getMetadataFor($entityName)->getName()
  484.         );
  485.     }
  486.     /**
  487.      * {@inheritDoc}
  488.      */
  489.     public function close()
  490.     {
  491.         $this->clear();
  492.         $this->closed true;
  493.     }
  494.     /**
  495.      * Tells the EntityManager to make an instance managed and persistent.
  496.      *
  497.      * The entity will be entered into the database at or before transaction
  498.      * commit or as a result of the flush operation.
  499.      *
  500.      * NOTE: The persist operation always considers entities that are not yet known to
  501.      * this EntityManager as NEW. Do not pass detached entities to the persist operation.
  502.      *
  503.      * @param object $entity The instance to make managed and persistent.
  504.      *
  505.      * @return void
  506.      *
  507.      * @throws ORMInvalidArgumentException
  508.      * @throws ORMException
  509.      */
  510.     public function persist($entity)
  511.     {
  512.         if ( ! is_object($entity)) {
  513.             throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()'$entity);
  514.         }
  515.         $this->errorIfClosed();
  516.         $this->unitOfWork->persist($entity);
  517.     }
  518.     /**
  519.      * Removes an entity instance.
  520.      *
  521.      * A removed entity will be removed from the database at or before transaction commit
  522.      * or as a result of the flush operation.
  523.      *
  524.      * @param object $entity The entity instance to remove.
  525.      *
  526.      * @return void
  527.      *
  528.      * @throws ORMInvalidArgumentException
  529.      * @throws ORMException
  530.      */
  531.     public function remove($entity)
  532.     {
  533.         if ( ! is_object($entity)) {
  534.             throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()'$entity);
  535.         }
  536.         $this->errorIfClosed();
  537.         $this->unitOfWork->remove($entity);
  538.     }
  539.     /**
  540.      * Refreshes the persistent state of an entity from the database,
  541.      * overriding any local changes that have not yet been persisted.
  542.      *
  543.      * @param object $entity The entity to refresh.
  544.      *
  545.      * @return void
  546.      *
  547.      * @throws ORMInvalidArgumentException
  548.      * @throws ORMException
  549.      */
  550.     public function refresh($entity)
  551.     {
  552.         if ( ! is_object($entity)) {
  553.             throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()'$entity);
  554.         }
  555.         $this->errorIfClosed();
  556.         $this->unitOfWork->refresh($entity);
  557.     }
  558.     /**
  559.      * Detaches an entity from the EntityManager, causing a managed entity to
  560.      * become detached.  Unflushed changes made to the entity if any
  561.      * (including removal of the entity), will not be synchronized to the database.
  562.      * Entities which previously referenced the detached entity will continue to
  563.      * reference it.
  564.      *
  565.      * @param object $entity The entity to detach.
  566.      *
  567.      * @return void
  568.      *
  569.      * @throws ORMInvalidArgumentException
  570.      *
  571.      * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  572.      */
  573.     public function detach($entity)
  574.     {
  575.         @trigger_error('Method ' __METHOD__ '() is deprecated and will be removed in Doctrine ORM 3.0.'E_USER_DEPRECATED);
  576.         if ( ! is_object($entity)) {
  577.             throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()'$entity);
  578.         }
  579.         $this->unitOfWork->detach($entity);
  580.     }
  581.     /**
  582.      * Merges the state of a detached entity into the persistence context
  583.      * of this EntityManager and returns the managed copy of the entity.
  584.      * The entity passed to merge will not become associated/managed with this EntityManager.
  585.      *
  586.      * @param object $entity The detached entity to merge into the persistence context.
  587.      *
  588.      * @return object The managed copy of the entity.
  589.      *
  590.      * @throws ORMInvalidArgumentException
  591.      * @throws ORMException
  592.      *
  593.      * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  594.      */
  595.     public function merge($entity)
  596.     {
  597.         @trigger_error('Method ' __METHOD__ '() is deprecated and will be removed in Doctrine ORM 3.0.'E_USER_DEPRECATED);
  598.         if ( ! is_object($entity)) {
  599.             throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()'$entity);
  600.         }
  601.         $this->errorIfClosed();
  602.         return $this->unitOfWork->merge($entity);
  603.     }
  604.     /**
  605.      * {@inheritDoc}
  606.      */
  607.     public function copy($entity$deep false)
  608.     {
  609.         @trigger_error('Method ' __METHOD__ '() is deprecated and will be removed in Doctrine ORM 3.0.'E_USER_DEPRECATED);
  610.         throw new \BadMethodCallException("Not implemented.");
  611.     }
  612.     /**
  613.      * {@inheritDoc}
  614.      */
  615.     public function lock($entity$lockMode$lockVersion null)
  616.     {
  617.         $this->unitOfWork->lock($entity$lockMode$lockVersion);
  618.     }
  619.     /**
  620.      * Gets the repository for an entity class.
  621.      *
  622.      * @param string $entityName The name of the entity.
  623.      *
  624.      * @return ObjectRepository|EntityRepository The repository class.
  625.      */
  626.     public function getRepository($entityName)
  627.     {
  628.         return $this->repositoryFactory->getRepository($this$entityName);
  629.     }
  630.     /**
  631.      * Determines whether an entity instance is managed in this EntityManager.
  632.      *
  633.      * @param object $entity
  634.      *
  635.      * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
  636.      */
  637.     public function contains($entity)
  638.     {
  639.         return $this->unitOfWork->isScheduledForInsert($entity)
  640.             || $this->unitOfWork->isInIdentityMap($entity)
  641.             && ! $this->unitOfWork->isScheduledForDelete($entity);
  642.     }
  643.     /**
  644.      * {@inheritDoc}
  645.      */
  646.     public function getEventManager()
  647.     {
  648.         return $this->eventManager;
  649.     }
  650.     /**
  651.      * {@inheritDoc}
  652.      */
  653.     public function getConfiguration()
  654.     {
  655.         return $this->config;
  656.     }
  657.     /**
  658.      * Throws an exception if the EntityManager is closed or currently not active.
  659.      *
  660.      * @return void
  661.      *
  662.      * @throws ORMException If the EntityManager is closed.
  663.      */
  664.     private function errorIfClosed()
  665.     {
  666.         if ($this->closed) {
  667.             throw ORMException::entityManagerClosed();
  668.         }
  669.     }
  670.     /**
  671.      * {@inheritDoc}
  672.      */
  673.     public function isOpen()
  674.     {
  675.         return (!$this->closed);
  676.     }
  677.     /**
  678.      * {@inheritDoc}
  679.      */
  680.     public function getUnitOfWork()
  681.     {
  682.         return $this->unitOfWork;
  683.     }
  684.     /**
  685.      * {@inheritDoc}
  686.      */
  687.     public function getHydrator($hydrationMode)
  688.     {
  689.         return $this->newHydrator($hydrationMode);
  690.     }
  691.     /**
  692.      * {@inheritDoc}
  693.      */
  694.     public function newHydrator($hydrationMode)
  695.     {
  696.         switch ($hydrationMode) {
  697.             case Query::HYDRATE_OBJECT:
  698.                 return new Internal\Hydration\ObjectHydrator($this);
  699.             case Query::HYDRATE_ARRAY:
  700.                 return new Internal\Hydration\ArrayHydrator($this);
  701.             case Query::HYDRATE_SCALAR:
  702.                 return new Internal\Hydration\ScalarHydrator($this);
  703.             case Query::HYDRATE_SINGLE_SCALAR:
  704.                 return new Internal\Hydration\SingleScalarHydrator($this);
  705.             case Query::HYDRATE_SIMPLEOBJECT:
  706.                 return new Internal\Hydration\SimpleObjectHydrator($this);
  707.             default:
  708.                 if (($class $this->config->getCustomHydrationMode($hydrationMode)) !== null) {
  709.                     return new $class($this);
  710.                 }
  711.         }
  712.         throw ORMException::invalidHydrationMode($hydrationMode);
  713.     }
  714.     /**
  715.      * {@inheritDoc}
  716.      */
  717.     public function getProxyFactory()
  718.     {
  719.         return $this->proxyFactory;
  720.     }
  721.     /**
  722.      * {@inheritDoc}
  723.      */
  724.     public function initializeObject($obj)
  725.     {
  726.         $this->unitOfWork->initializeObject($obj);
  727.     }
  728.     /**
  729.      * Factory method to create EntityManager instances.
  730.      *
  731.      * @param array|Connection $connection   An array with the connection parameters or an existing Connection instance.
  732.      * @param Configuration    $config       The Configuration instance to use.
  733.      * @param EventManager     $eventManager The EventManager instance to use.
  734.      *
  735.      * @return EntityManager The created EntityManager.
  736.      *
  737.      * @throws \InvalidArgumentException
  738.      * @throws ORMException
  739.      */
  740.     public static function create($connectionConfiguration $configEventManager $eventManager null)
  741.     {
  742.         if ( ! $config->getMetadataDriverImpl()) {
  743.             throw ORMException::missingMappingDriverImpl();
  744.         }
  745.         $connection = static::createConnection($connection$config$eventManager);
  746.         return new EntityManager($connection$config$connection->getEventManager());
  747.     }
  748.     /**
  749.      * Factory method to create Connection instances.
  750.      *
  751.      * @param array|Connection $connection   An array with the connection parameters or an existing Connection instance.
  752.      * @param Configuration    $config       The Configuration instance to use.
  753.      * @param EventManager     $eventManager The EventManager instance to use.
  754.      *
  755.      * @return Connection
  756.      *
  757.      * @throws \InvalidArgumentException
  758.      * @throws ORMException
  759.      */
  760.     protected static function createConnection($connectionConfiguration $configEventManager $eventManager null)
  761.     {
  762.         if (is_array($connection)) {
  763.             return DriverManager::getConnection($connection$config$eventManager ?: new EventManager());
  764.         }
  765.         if ( ! $connection instanceof Connection) {
  766.             throw new \InvalidArgumentException(
  767.                 sprintf(
  768.                     'Invalid $connection argument of type %s given%s.',
  769.                     is_object($connection) ? get_class($connection) : gettype($connection),
  770.                     is_object($connection) ? '' ': "' $connection '"'
  771.                 )
  772.             );
  773.         }
  774.         if ($eventManager !== null && $connection->getEventManager() !== $eventManager) {
  775.             throw ORMException::mismatchedEventManager();
  776.         }
  777.         return $connection;
  778.     }
  779.     /**
  780.      * {@inheritDoc}
  781.      */
  782.     public function getFilters()
  783.     {
  784.         if (null === $this->filterCollection) {
  785.             $this->filterCollection = new FilterCollection($this);
  786.         }
  787.         return $this->filterCollection;
  788.     }
  789.     /**
  790.      * {@inheritDoc}
  791.      */
  792.     public function isFiltersStateClean()
  793.     {
  794.         return null === $this->filterCollection || $this->filterCollection->isClean();
  795.     }
  796.     /**
  797.      * {@inheritDoc}
  798.      */
  799.     public function hasFilters()
  800.     {
  801.         return null !== $this->filterCollection;
  802.     }
  803.     /**
  804.      * @param int $lockMode
  805.      * @param ClassMetadata $class
  806.      * @throws OptimisticLockException
  807.      * @throws TransactionRequiredException
  808.      */
  809.     private function checkLockRequirements(int $lockModeClassMetadata $class): void
  810.     {
  811.         switch ($lockMode) {
  812.             case LockMode::OPTIMISTIC:
  813.                 if (!$class->isVersioned) {
  814.                     throw OptimisticLockException::notVersioned($class->name);
  815.                 }
  816.                 break;
  817.             case LockMode::PESSIMISTIC_READ:
  818.             case LockMode::PESSIMISTIC_WRITE:
  819.                 if (!$this->getConnection()->isTransactionActive()) {
  820.                     throw TransactionRequiredException::transactionRequired();
  821.                 }
  822.         }
  823.     }
  824. }