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

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 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 = ClassUtils::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. $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
  484. $entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName);
  485. // Check identity map first, if its already in there just return it.
  486. if ($entity !== false) {
  487. return $entity instanceof $class->name ? $entity : null;
  488. }
  489. if (! is_array($identifier)) {
  490. $identifier = [$class->identifier[0] => $identifier];
  491. }
  492. $entity = $class->newInstance();
  493. $class->setIdentifierValues($entity, $identifier);
  494. $this->unitOfWork->registerManaged($entity, $identifier, []);
  495. $this->unitOfWork->markReadOnly($entity);
  496. return $entity;
  497. }
  498. /**
  499. * Clears the EntityManager. All entities that are currently managed
  500. * by this EntityManager become detached.
  501. *
  502. * @param string|null $entityName if given, only entities of this type will get detached
  503. *
  504. * @return void
  505. *
  506. * @throws ORMInvalidArgumentException If a non-null non-string value is given.
  507. * @throws MappingException If a $entityName is given, but that entity is not
  508. * found in the mappings.
  509. */
  510. public function clear($entityName = null)
  511. {
  512. if ($entityName !== null && ! is_string($entityName)) {
  513. throw ORMInvalidArgumentException::invalidEntityName($entityName);
  514. }
  515. if ($entityName !== null) {
  516. Deprecation::trigger(
  517. 'doctrine/orm',
  518. 'https://github.com/doctrine/orm/issues/8460',
  519. 'Calling %s() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
  520. __METHOD__
  521. );
  522. }
  523. $this->unitOfWork->clear(
  524. $entityName === null
  525. ? null
  526. : $this->metadataFactory->getMetadataFor($entityName)->getName()
  527. );
  528. }
  529. /**
  530. * {@inheritDoc}
  531. */
  532. public function close()
  533. {
  534. $this->clear();
  535. $this->closed = true;
  536. }
  537. /**
  538. * Tells the EntityManager to make an instance managed and persistent.
  539. *
  540. * The entity will be entered into the database at or before transaction
  541. * commit or as a result of the flush operation.
  542. *
  543. * NOTE: The persist operation always considers entities that are not yet known to
  544. * this EntityManager as NEW. Do not pass detached entities to the persist operation.
  545. *
  546. * @param object $entity The instance to make managed and persistent.
  547. *
  548. * @return void
  549. *
  550. * @throws ORMInvalidArgumentException
  551. * @throws ORMException
  552. */
  553. public function persist($entity)
  554. {
  555. if (! is_object($entity)) {
  556. throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity);
  557. }
  558. $this->errorIfClosed();
  559. $this->unitOfWork->persist($entity);
  560. }
  561. /**
  562. * Removes an entity instance.
  563. *
  564. * A removed entity will be removed from the database at or before transaction commit
  565. * or as a result of the flush operation.
  566. *
  567. * @param object $entity The entity instance to remove.
  568. *
  569. * @return void
  570. *
  571. * @throws ORMInvalidArgumentException
  572. * @throws ORMException
  573. */
  574. public function remove($entity)
  575. {
  576. if (! is_object($entity)) {
  577. throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()', $entity);
  578. }
  579. $this->errorIfClosed();
  580. $this->unitOfWork->remove($entity);
  581. }
  582. /**
  583. * Refreshes the persistent state of an entity from the database,
  584. * overriding any local changes that have not yet been persisted.
  585. *
  586. * @param object $entity The entity to refresh
  587. * @psalm-param LockMode::*|null $lockMode
  588. *
  589. * @return void
  590. *
  591. * @throws ORMInvalidArgumentException
  592. * @throws ORMException
  593. * @throws TransactionRequiredException
  594. */
  595. public function refresh($entity, ?int $lockMode = null)
  596. {
  597. if (! is_object($entity)) {
  598. throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity);
  599. }
  600. $this->errorIfClosed();
  601. $this->unitOfWork->refresh($entity, $lockMode);
  602. }
  603. /**
  604. * Detaches an entity from the EntityManager, causing a managed entity to
  605. * become detached. Unflushed changes made to the entity if any
  606. * (including removal of the entity), will not be synchronized to the database.
  607. * Entities which previously referenced the detached entity will continue to
  608. * reference it.
  609. *
  610. * @param object $entity The entity to detach.
  611. *
  612. * @return void
  613. *
  614. * @throws ORMInvalidArgumentException
  615. */
  616. public function detach($entity)
  617. {
  618. if (! is_object($entity)) {
  619. throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity);
  620. }
  621. $this->unitOfWork->detach($entity);
  622. }
  623. /**
  624. * Merges the state of a detached entity into the persistence context
  625. * of this EntityManager and returns the managed copy of the entity.
  626. * The entity passed to merge will not become associated/managed with this EntityManager.
  627. *
  628. * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  629. *
  630. * @param object $entity The detached entity to merge into the persistence context.
  631. *
  632. * @return object The managed copy of the entity.
  633. *
  634. * @throws ORMInvalidArgumentException
  635. * @throws ORMException
  636. */
  637. public function merge($entity)
  638. {
  639. Deprecation::trigger(
  640. 'doctrine/orm',
  641. 'https://github.com/doctrine/orm/issues/8461',
  642. 'Method %s() is deprecated and will be removed in Doctrine ORM 3.0.',
  643. __METHOD__
  644. );
  645. if (! is_object($entity)) {
  646. throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity);
  647. }
  648. $this->errorIfClosed();
  649. return $this->unitOfWork->merge($entity);
  650. }
  651. /**
  652. * {@inheritDoc}
  653. *
  654. * @psalm-return never
  655. */
  656. public function copy($entity, $deep = false)
  657. {
  658. Deprecation::trigger(
  659. 'doctrine/orm',
  660. 'https://github.com/doctrine/orm/issues/8462',
  661. 'Method %s() is deprecated and will be removed in Doctrine ORM 3.0.',
  662. __METHOD__
  663. );
  664. throw new BadMethodCallException('Not implemented.');
  665. }
  666. /**
  667. * {@inheritDoc}
  668. */
  669. public function lock($entity, $lockMode, $lockVersion = null)
  670. {
  671. $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
  672. }
  673. /**
  674. * Gets the repository for an entity class.
  675. *
  676. * @param string $entityName The name of the entity.
  677. * @psalm-param class-string<T> $entityName
  678. *
  679. * @return ObjectRepository|EntityRepository The repository class.
  680. * @psalm-return EntityRepository<T>
  681. *
  682. * @template T of object
  683. */
  684. public function getRepository($entityName)
  685. {
  686. if (strpos($entityName, ':') !== false) {
  687. if (class_exists(PersistentObject::class)) {
  688. Deprecation::trigger(
  689. 'doctrine/orm',
  690. 'https://github.com/doctrine/orm/issues/8818',
  691. 'Short namespace aliases such as "%s" are deprecated and will be removed in Doctrine ORM 3.0.',
  692. $entityName
  693. );
  694. } else {
  695. throw NotSupported::createForPersistence3(sprintf(
  696. 'Using short namespace alias "%s" when calling %s',
  697. $entityName,
  698. __METHOD__
  699. ));
  700. }
  701. }
  702. $repository = $this->repositoryFactory->getRepository($this, $entityName);
  703. if (! $repository instanceof EntityRepository) {
  704. Deprecation::trigger(
  705. 'doctrine/orm',
  706. 'https://github.com/doctrine/orm/pull/9533',
  707. 'Not returning an instance of %s from %s::getRepository() is deprecated and will cause a TypeError on 3.0.',
  708. EntityRepository::class,
  709. get_debug_type($this->repositoryFactory)
  710. );
  711. }
  712. return $repository;
  713. }
  714. /**
  715. * Determines whether an entity instance is managed in this EntityManager.
  716. *
  717. * @param object $entity
  718. *
  719. * @return bool TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
  720. */
  721. public function contains($entity)
  722. {
  723. return $this->unitOfWork->isScheduledForInsert($entity)
  724. || $this->unitOfWork->isInIdentityMap($entity)
  725. && ! $this->unitOfWork->isScheduledForDelete($entity);
  726. }
  727. /**
  728. * {@inheritDoc}
  729. */
  730. public function getEventManager()
  731. {
  732. return $this->eventManager;
  733. }
  734. /**
  735. * {@inheritDoc}
  736. */
  737. public function getConfiguration()
  738. {
  739. return $this->config;
  740. }
  741. /**
  742. * Throws an exception if the EntityManager is closed or currently not active.
  743. *
  744. * @throws EntityManagerClosed If the EntityManager is closed.
  745. */
  746. private function errorIfClosed(): void
  747. {
  748. if ($this->closed) {
  749. throw EntityManagerClosed::create();
  750. }
  751. }
  752. /**
  753. * {@inheritDoc}
  754. */
  755. public function isOpen()
  756. {
  757. return ! $this->closed;
  758. }
  759. /**
  760. * {@inheritDoc}
  761. */
  762. public function getUnitOfWork()
  763. {
  764. return $this->unitOfWork;
  765. }
  766. /**
  767. * {@inheritDoc}
  768. */
  769. public function getHydrator($hydrationMode)
  770. {
  771. return $this->newHydrator($hydrationMode);
  772. }
  773. /**
  774. * {@inheritDoc}
  775. */
  776. public function newHydrator($hydrationMode)
  777. {
  778. switch ($hydrationMode) {
  779. case Query::HYDRATE_OBJECT:
  780. return new Internal\Hydration\ObjectHydrator($this);
  781. case Query::HYDRATE_ARRAY:
  782. return new Internal\Hydration\ArrayHydrator($this);
  783. case Query::HYDRATE_SCALAR:
  784. return new Internal\Hydration\ScalarHydrator($this);
  785. case Query::HYDRATE_SINGLE_SCALAR:
  786. return new Internal\Hydration\SingleScalarHydrator($this);
  787. case Query::HYDRATE_SIMPLEOBJECT:
  788. return new Internal\Hydration\SimpleObjectHydrator($this);
  789. case Query::HYDRATE_SCALAR_COLUMN:
  790. return new Internal\Hydration\ScalarColumnHydrator($this);
  791. default:
  792. $class = $this->config->getCustomHydrationMode($hydrationMode);
  793. if ($class !== null) {
  794. return new $class($this);
  795. }
  796. }
  797. throw InvalidHydrationMode::fromMode((string) $hydrationMode);
  798. }
  799. /**
  800. * {@inheritDoc}
  801. */
  802. public function getProxyFactory()
  803. {
  804. return $this->proxyFactory;
  805. }
  806. /**
  807. * {@inheritDoc}
  808. */
  809. public function initializeObject($obj)
  810. {
  811. $this->unitOfWork->initializeObject($obj);
  812. }
  813. /**
  814. * Factory method to create EntityManager instances.
  815. *
  816. * @deprecated Use {@see DriverManager::getConnection()} to bootstrap the connection and call the constructor.
  817. *
  818. * @param mixed[]|Connection $connection An array with the connection parameters or an existing Connection instance.
  819. * @param Configuration $config The Configuration instance to use.
  820. * @param EventManager|null $eventManager The EventManager instance to use.
  821. * @psalm-param array<string, mixed>|Connection $connection
  822. *
  823. * @return EntityManager The created EntityManager.
  824. *
  825. * @throws InvalidArgumentException
  826. * @throws ORMException
  827. */
  828. public static function create($connection, Configuration $config, ?EventManager $eventManager = null)
  829. {
  830. Deprecation::trigger(
  831. 'doctrine/orm',
  832. 'https://github.com/doctrine/orm/pull/9961',
  833. '%s() is deprecated. To boostrap a DBAL connection, call %s::getConnection() instead. Use the constructor to create an instance of %s.',
  834. __METHOD__,
  835. DriverManager::class,
  836. self::class
  837. );
  838. $connection = static::createConnection($connection, $config, $eventManager);
  839. return new EntityManager($connection, $config);
  840. }
  841. /**
  842. * Factory method to create Connection instances.
  843. *
  844. * @deprecated Use {@see DriverManager::getConnection()} to bootstrap the connection.
  845. *
  846. * @param mixed[]|Connection $connection An array with the connection parameters or an existing Connection instance.
  847. * @param Configuration $config The Configuration instance to use.
  848. * @param EventManager|null $eventManager The EventManager instance to use.
  849. * @psalm-param array<string, mixed>|Connection $connection
  850. *
  851. * @return Connection
  852. *
  853. * @throws InvalidArgumentException
  854. * @throws ORMException
  855. */
  856. protected static function createConnection($connection, Configuration $config, ?EventManager $eventManager = null)
  857. {
  858. Deprecation::triggerIfCalledFromOutside(
  859. 'doctrine/orm',
  860. 'https://github.com/doctrine/orm/pull/9961',
  861. '%s() is deprecated, call %s::getConnection() instead.',
  862. __METHOD__,
  863. DriverManager::class
  864. );
  865. if (is_array($connection)) {
  866. return DriverManager::getConnection($connection, $config, $eventManager ?: new EventManager());
  867. }
  868. if (! $connection instanceof Connection) {
  869. throw new InvalidArgumentException(
  870. sprintf(
  871. 'Invalid $connection argument of type %s given%s.',
  872. get_debug_type($connection),
  873. is_object($connection) ? '' : ': "' . $connection . '"'
  874. )
  875. );
  876. }
  877. if ($eventManager !== null && $connection->getEventManager() !== $eventManager) {
  878. throw MismatchedEventManager::create();
  879. }
  880. return $connection;
  881. }
  882. /**
  883. * {@inheritDoc}
  884. */
  885. public function getFilters()
  886. {
  887. if ($this->filterCollection === null) {
  888. $this->filterCollection = new FilterCollection($this);
  889. }
  890. return $this->filterCollection;
  891. }
  892. /**
  893. * {@inheritDoc}
  894. */
  895. public function isFiltersStateClean()
  896. {
  897. return $this->filterCollection === null || $this->filterCollection->isClean();
  898. }
  899. /**
  900. * {@inheritDoc}
  901. */
  902. public function hasFilters()
  903. {
  904. return $this->filterCollection !== null;
  905. }
  906. /**
  907. * @psalm-param LockMode::* $lockMode
  908. *
  909. * @throws OptimisticLockException
  910. * @throws TransactionRequiredException
  911. */
  912. private function checkLockRequirements(int $lockMode, ClassMetadata $class): void
  913. {
  914. switch ($lockMode) {
  915. case LockMode::OPTIMISTIC:
  916. if (! $class->isVersioned) {
  917. throw OptimisticLockException::notVersioned($class->name);
  918. }
  919. break;
  920. case LockMode::PESSIMISTIC_READ:
  921. case LockMode::PESSIMISTIC_WRITE:
  922. if (! $this->getConnection()->isTransactionActive()) {
  923. throw TransactionRequiredException::transactionRequired();
  924. }
  925. }
  926. }
  927. private function configureMetadataCache(): void
  928. {
  929. $metadataCache = $this->config->getMetadataCache();
  930. if (! $metadataCache) {
  931. $this->configureLegacyMetadataCache();
  932. return;
  933. }
  934. $this->metadataFactory->setCache($metadataCache);
  935. }
  936. private function configureLegacyMetadataCache(): void
  937. {
  938. $metadataCache = $this->config->getMetadataCacheImpl();
  939. if (! $metadataCache) {
  940. return;
  941. }
  942. // Wrap doctrine/cache to provide PSR-6 interface
  943. $this->metadataFactory->setCache(CacheAdapter::wrap($metadataCache));
  944. }
  945. }