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

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