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

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