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

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