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

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