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.                 $unitOfWork->lock($entity$lockMode$lockVersion);
  409.                 return $entity;
  410.             case $lockMode === LockMode::PESSIMISTIC_READ:
  411.             case $lockMode === LockMode::PESSIMISTIC_WRITE:
  412.                 return $persister->load($sortedIdnullnull, [], $lockMode);
  413.             default:
  414.                 return $persister->loadById($sortedId);
  415.         }
  416.     }
  417.     /**
  418.      * {@inheritDoc}
  419.      */
  420.     public function getReference($entityName$id)
  421.     {
  422.         $class $this->metadataFactory->getMetadataFor(ltrim($entityName'\\'));
  423.         if (! is_array($id)) {
  424.             $id = [$class->identifier[0] => $id];
  425.         }
  426.         $sortedId = [];
  427.         foreach ($class->identifier as $identifier) {
  428.             if (! isset($id[$identifier])) {
  429.                 throw ORMException::missingIdentifierField($class->name$identifier);
  430.             }
  431.             $sortedId[$identifier] = $id[$identifier];
  432.             unset($id[$identifier]);
  433.         }
  434.         if ($id) {
  435.             throw ORMException::unrecognizedIdentifierFields($class->namearray_keys($id));
  436.         }
  437.         $entity $this->unitOfWork->tryGetById($sortedId$class->rootEntityName);
  438.         // Check identity map first, if its already in there just return it.
  439.         if ($entity !== false) {
  440.             return $entity instanceof $class->name $entity null;
  441.         }
  442.         if ($class->subClasses) {
  443.             return $this->find($entityName$sortedId);
  444.         }
  445.         $entity $this->proxyFactory->getProxy($class->name$sortedId);
  446.         $this->unitOfWork->registerManaged($entity$sortedId, []);
  447.         return $entity;
  448.     }
  449.     /**
  450.      * {@inheritDoc}
  451.      */
  452.     public function getPartialReference($entityName$identifier)
  453.     {
  454.         $class $this->metadataFactory->getMetadataFor(ltrim($entityName'\\'));
  455.         $entity $this->unitOfWork->tryGetById($identifier$class->rootEntityName);
  456.         // Check identity map first, if its already in there just return it.
  457.         if ($entity !== false) {
  458.             return $entity instanceof $class->name $entity null;
  459.         }
  460.         if (! is_array($identifier)) {
  461.             $identifier = [$class->identifier[0] => $identifier];
  462.         }
  463.         $entity $class->newInstance();
  464.         $class->setIdentifierValues($entity$identifier);
  465.         $this->unitOfWork->registerManaged($entity$identifier, []);
  466.         $this->unitOfWork->markReadOnly($entity);
  467.         return $entity;
  468.     }
  469.     /**
  470.      * Clears the EntityManager. All entities that are currently managed
  471.      * by this EntityManager become detached.
  472.      *
  473.      * @param string|null $entityName if given, only entities of this type will get detached
  474.      *
  475.      * @return void
  476.      *
  477.      * @throws ORMInvalidArgumentException If a non-null non-string value is given.
  478.      * @throws MappingException            If a $entityName is given, but that entity is not
  479.      *                                     found in the mappings.
  480.      */
  481.     public function clear($entityName null)
  482.     {
  483.         if ($entityName !== null && ! is_string($entityName)) {
  484.             throw ORMInvalidArgumentException::invalidEntityName($entityName);
  485.         }
  486.         if ($entityName !== null) {
  487.             Deprecation::trigger(
  488.                 'doctrine/orm',
  489.                 'https://github.com/doctrine/orm/issues/8460',
  490.                 'Calling %s() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
  491.                 __METHOD__
  492.             );
  493.         }
  494.         $this->unitOfWork->clear(
  495.             $entityName === null
  496.                 null
  497.                 $this->metadataFactory->getMetadataFor($entityName)->getName()
  498.         );
  499.     }
  500.     /**
  501.      * {@inheritDoc}
  502.      */
  503.     public function close()
  504.     {
  505.         $this->clear();
  506.         $this->closed true;
  507.     }
  508.     /**
  509.      * Tells the EntityManager to make an instance managed and persistent.
  510.      *
  511.      * The entity will be entered into the database at or before transaction
  512.      * commit or as a result of the flush operation.
  513.      *
  514.      * NOTE: The persist operation always considers entities that are not yet known to
  515.      * this EntityManager as NEW. Do not pass detached entities to the persist operation.
  516.      *
  517.      * @param object $entity The instance to make managed and persistent.
  518.      *
  519.      * @return void
  520.      *
  521.      * @throws ORMInvalidArgumentException
  522.      * @throws ORMException
  523.      */
  524.     public function persist($entity)
  525.     {
  526.         if (! is_object($entity)) {
  527.             throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()'$entity);
  528.         }
  529.         $this->errorIfClosed();
  530.         $this->unitOfWork->persist($entity);
  531.     }
  532.     /**
  533.      * Removes an entity instance.
  534.      *
  535.      * A removed entity will be removed from the database at or before transaction commit
  536.      * or as a result of the flush operation.
  537.      *
  538.      * @param object $entity The entity instance to remove.
  539.      *
  540.      * @return void
  541.      *
  542.      * @throws ORMInvalidArgumentException
  543.      * @throws ORMException
  544.      */
  545.     public function remove($entity)
  546.     {
  547.         if (! is_object($entity)) {
  548.             throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()'$entity);
  549.         }
  550.         $this->errorIfClosed();
  551.         $this->unitOfWork->remove($entity);
  552.     }
  553.     /**
  554.      * Refreshes the persistent state of an entity from the database,
  555.      * overriding any local changes that have not yet been persisted.
  556.      *
  557.      * @param object $entity The entity to refresh.
  558.      *
  559.      * @return void
  560.      *
  561.      * @throws ORMInvalidArgumentException
  562.      * @throws ORMException
  563.      */
  564.     public function refresh($entity)
  565.     {
  566.         if (! is_object($entity)) {
  567.             throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()'$entity);
  568.         }
  569.         $this->errorIfClosed();
  570.         $this->unitOfWork->refresh($entity);
  571.     }
  572.     /**
  573.      * Detaches an entity from the EntityManager, causing a managed entity to
  574.      * become detached.  Unflushed changes made to the entity if any
  575.      * (including removal of the entity), will not be synchronized to the database.
  576.      * Entities which previously referenced the detached entity will continue to
  577.      * reference it.
  578.      *
  579.      * @param object $entity The entity to detach.
  580.      *
  581.      * @return void
  582.      *
  583.      * @throws ORMInvalidArgumentException
  584.      */
  585.     public function detach($entity)
  586.     {
  587.         if (! is_object($entity)) {
  588.             throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()'$entity);
  589.         }
  590.         $this->unitOfWork->detach($entity);
  591.     }
  592.     /**
  593.      * Merges the state of a detached entity into the persistence context
  594.      * of this EntityManager and returns the managed copy of the entity.
  595.      * The entity passed to merge will not become associated/managed with this EntityManager.
  596.      *
  597.      * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  598.      *
  599.      * @param object $entity The detached entity to merge into the persistence context.
  600.      *
  601.      * @return object The managed copy of the entity.
  602.      *
  603.      * @throws ORMInvalidArgumentException
  604.      * @throws ORMException
  605.      */
  606.     public function merge($entity)
  607.     {
  608.         Deprecation::trigger(
  609.             'doctrine/orm',
  610.             'https://github.com/doctrine/orm/issues/8461',
  611.             'Method %s() is deprecated and will be removed in Doctrine ORM 3.0.',
  612.             __METHOD__
  613.         );
  614.         if (! is_object($entity)) {
  615.             throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()'$entity);
  616.         }
  617.         $this->errorIfClosed();
  618.         return $this->unitOfWork->merge($entity);
  619.     }
  620.     /**
  621.      * {@inheritDoc}
  622.      */
  623.     public function copy($entity$deep false)
  624.     {
  625.         Deprecation::trigger(
  626.             'doctrine/orm',
  627.             'https://github.com/doctrine/orm/issues/8462',
  628.             'Method %s() is deprecated and will be removed in Doctrine ORM 3.0.',
  629.             __METHOD__
  630.         );
  631.         throw new BadMethodCallException('Not implemented.');
  632.     }
  633.     /**
  634.      * {@inheritDoc}
  635.      */
  636.     public function lock($entity$lockMode$lockVersion null)
  637.     {
  638.         $this->unitOfWork->lock($entity$lockMode$lockVersion);
  639.     }
  640.     /**
  641.      * Gets the repository for an entity class.
  642.      *
  643.      * @param string $entityName The name of the entity.
  644.      * @psalm-param class-string<T> $entityName
  645.      *
  646.      * @return ObjectRepository|EntityRepository The repository class.
  647.      * @psalm-return EntityRepository<T>
  648.      *
  649.      * @template T
  650.      */
  651.     public function getRepository($entityName)
  652.     {
  653.         return $this->repositoryFactory->getRepository($this$entityName);
  654.     }
  655.     /**
  656.      * Determines whether an entity instance is managed in this EntityManager.
  657.      *
  658.      * @param object $entity
  659.      *
  660.      * @return bool TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
  661.      */
  662.     public function contains($entity)
  663.     {
  664.         return $this->unitOfWork->isScheduledForInsert($entity)
  665.             || $this->unitOfWork->isInIdentityMap($entity)
  666.             && ! $this->unitOfWork->isScheduledForDelete($entity);
  667.     }
  668.     /**
  669.      * {@inheritDoc}
  670.      */
  671.     public function getEventManager()
  672.     {
  673.         return $this->eventManager;
  674.     }
  675.     /**
  676.      * {@inheritDoc}
  677.      */
  678.     public function getConfiguration()
  679.     {
  680.         return $this->config;
  681.     }
  682.     /**
  683.      * Throws an exception if the EntityManager is closed or currently not active.
  684.      *
  685.      * @throws ORMException If the EntityManager is closed.
  686.      */
  687.     private function errorIfClosed(): void
  688.     {
  689.         if ($this->closed) {
  690.             throw ORMException::entityManagerClosed();
  691.         }
  692.     }
  693.     /**
  694.      * {@inheritDoc}
  695.      */
  696.     public function isOpen()
  697.     {
  698.         return ! $this->closed;
  699.     }
  700.     /**
  701.      * {@inheritDoc}
  702.      */
  703.     public function getUnitOfWork()
  704.     {
  705.         return $this->unitOfWork;
  706.     }
  707.     /**
  708.      * {@inheritDoc}
  709.      */
  710.     public function getHydrator($hydrationMode)
  711.     {
  712.         return $this->newHydrator($hydrationMode);
  713.     }
  714.     /**
  715.      * {@inheritDoc}
  716.      */
  717.     public function newHydrator($hydrationMode)
  718.     {
  719.         switch ($hydrationMode) {
  720.             case Query::HYDRATE_OBJECT:
  721.                 return new Internal\Hydration\ObjectHydrator($this);
  722.             case Query::HYDRATE_ARRAY:
  723.                 return new Internal\Hydration\ArrayHydrator($this);
  724.             case Query::HYDRATE_SCALAR:
  725.                 return new Internal\Hydration\ScalarHydrator($this);
  726.             case Query::HYDRATE_SINGLE_SCALAR:
  727.                 return new Internal\Hydration\SingleScalarHydrator($this);
  728.             case Query::HYDRATE_SIMPLEOBJECT:
  729.                 return new Internal\Hydration\SimpleObjectHydrator($this);
  730.             default:
  731.                 $class $this->config->getCustomHydrationMode($hydrationMode);
  732.                 if ($class !== null) {
  733.                     return new $class($this);
  734.                 }
  735.         }
  736.         throw ORMException::invalidHydrationMode($hydrationMode);
  737.     }
  738.     /**
  739.      * {@inheritDoc}
  740.      */
  741.     public function getProxyFactory()
  742.     {
  743.         return $this->proxyFactory;
  744.     }
  745.     /**
  746.      * {@inheritDoc}
  747.      */
  748.     public function initializeObject($obj)
  749.     {
  750.         $this->unitOfWork->initializeObject($obj);
  751.     }
  752.     /**
  753.      * Factory method to create EntityManager instances.
  754.      *
  755.      * @param mixed[]|Connection $connection   An array with the connection parameters or an existing Connection instance.
  756.      * @param Configuration      $config       The Configuration instance to use.
  757.      * @param EventManager|null  $eventManager The EventManager instance to use.
  758.      * @psalm-param array<string, mixed>|Connection $connection
  759.      *
  760.      * @return EntityManager The created EntityManager.
  761.      *
  762.      * @throws InvalidArgumentException
  763.      * @throws ORMException
  764.      */
  765.     public static function create($connectionConfiguration $config, ?EventManager $eventManager null)
  766.     {
  767.         if (! $config->getMetadataDriverImpl()) {
  768.             throw ORMException::missingMappingDriverImpl();
  769.         }
  770.         $connection = static::createConnection($connection$config$eventManager);
  771.         return new EntityManager($connection$config$connection->getEventManager());
  772.     }
  773.     /**
  774.      * Factory method to create Connection instances.
  775.      *
  776.      * @param mixed[]|Connection $connection   An array with the connection parameters or an existing Connection instance.
  777.      * @param Configuration      $config       The Configuration instance to use.
  778.      * @param EventManager|null  $eventManager The EventManager instance to use.
  779.      * @psalm-param array<string, mixed>|Connection $connection
  780.      *
  781.      * @return Connection
  782.      *
  783.      * @throws InvalidArgumentException
  784.      * @throws ORMException
  785.      */
  786.     protected static function createConnection($connectionConfiguration $config, ?EventManager $eventManager null)
  787.     {
  788.         if (is_array($connection)) {
  789.             return DriverManager::getConnection($connection$config$eventManager ?: new EventManager());
  790.         }
  791.         if (! $connection instanceof Connection) {
  792.             throw new InvalidArgumentException(
  793.                 sprintf(
  794.                     'Invalid $connection argument of type %s given%s.',
  795.                     is_object($connection) ? get_class($connection) : gettype($connection),
  796.                     is_object($connection) ? '' ': "' $connection '"'
  797.                 )
  798.             );
  799.         }
  800.         if ($eventManager !== null && $connection->getEventManager() !== $eventManager) {
  801.             throw ORMException::mismatchedEventManager();
  802.         }
  803.         return $connection;
  804.     }
  805.     /**
  806.      * {@inheritDoc}
  807.      */
  808.     public function getFilters()
  809.     {
  810.         if ($this->filterCollection === null) {
  811.             $this->filterCollection = new FilterCollection($this);
  812.         }
  813.         return $this->filterCollection;
  814.     }
  815.     /**
  816.      * {@inheritDoc}
  817.      */
  818.     public function isFiltersStateClean()
  819.     {
  820.         return $this->filterCollection === null || $this->filterCollection->isClean();
  821.     }
  822.     /**
  823.      * {@inheritDoc}
  824.      */
  825.     public function hasFilters()
  826.     {
  827.         return $this->filterCollection !== null;
  828.     }
  829.     /**
  830.      * @throws OptimisticLockException
  831.      * @throws TransactionRequiredException
  832.      */
  833.     private function checkLockRequirements(int $lockModeClassMetadata $class): void
  834.     {
  835.         switch ($lockMode) {
  836.             case LockMode::OPTIMISTIC:
  837.                 if (! $class->isVersioned) {
  838.                     throw OptimisticLockException::notVersioned($class->name);
  839.                 }
  840.                 break;
  841.             case LockMode::PESSIMISTIC_READ:
  842.             case LockMode::PESSIMISTIC_WRITE:
  843.                 if (! $this->getConnection()->isTransactionActive()) {
  844.                     throw TransactionRequiredException::transactionRequired();
  845.                 }
  846.         }
  847.     }
  848.     private function configureMetadataCache(): void
  849.     {
  850.         $metadataCache $this->config->getMetadataCache();
  851.         if (! $metadataCache) {
  852.             $this->configureLegacyMetadataCache();
  853.             return;
  854.         }
  855.         // We have a PSR-6 compatible metadata factory. Use cache directly
  856.         if (method_exists($this->metadataFactory'setCache')) {
  857.             $this->metadataFactory->setCache($metadataCache);
  858.             return;
  859.         }
  860.         // Wrap PSR-6 cache to provide doctrine/cache interface
  861.         $this->metadataFactory->setCacheDriver(DoctrineProvider::wrap($metadataCache));
  862.     }
  863.     private function configureLegacyMetadataCache(): void
  864.     {
  865.         $metadataCache $this->config->getMetadataCacheImpl();
  866.         if (! $metadataCache) {
  867.             return;
  868.         }
  869.         // Metadata factory is not PSR-6 compatible. Use cache directly
  870.         if (! method_exists($this->metadataFactory'setCache')) {
  871.             $this->metadataFactory->setCacheDriver($metadataCache);
  872.             return;
  873.         }
  874.         // Wrap doctrine/cache to provide PSR-6 interface
  875.         $this->metadataFactory->setCache(CacheAdapter::wrap($metadataCache));
  876.     }
  877. }