vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php line460

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