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

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