vendor/doctrine/orm/src/EntityManager.php line 812

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