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

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