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

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