EntityManager.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM;
  20. use Exception,
  21. Doctrine\Common\EventManager,
  22. Doctrine\Common\Persistence\ObjectManager,
  23. Doctrine\DBAL\Connection,
  24. Doctrine\DBAL\LockMode,
  25. Doctrine\ORM\Mapping\ClassMetadata,
  26. Doctrine\ORM\Mapping\ClassMetadataFactory,
  27. Doctrine\ORM\Query\ResultSetMapping,
  28. Doctrine\ORM\Proxy\ProxyFactory,
  29. Doctrine\ORM\Query\FilterCollection;
  30. /**
  31. * The EntityManager is the central access point to ORM functionality.
  32. *
  33. * @since 2.0
  34. * @author Benjamin Eberlei <kontakt@beberlei.de>
  35. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  36. * @author Jonathan Wage <jonwage@gmail.com>
  37. * @author Roman Borschel <roman@code-factory.org>
  38. */
  39. class EntityManager implements ObjectManager
  40. {
  41. /**
  42. * The used Configuration.
  43. *
  44. * @var \Doctrine\ORM\Configuration
  45. */
  46. private $config;
  47. /**
  48. * The database connection used by the EntityManager.
  49. *
  50. * @var \Doctrine\DBAL\Connection
  51. */
  52. private $conn;
  53. /**
  54. * The metadata factory, used to retrieve the ORM metadata of entity classes.
  55. *
  56. * @var \Doctrine\ORM\Mapping\ClassMetadataFactory
  57. */
  58. private $metadataFactory;
  59. /**
  60. * The EntityRepository instances.
  61. *
  62. * @var array
  63. */
  64. private $repositories = array();
  65. /**
  66. * The UnitOfWork used to coordinate object-level transactions.
  67. *
  68. * @var \Doctrine\ORM\UnitOfWork
  69. */
  70. private $unitOfWork;
  71. /**
  72. * The event manager that is the central point of the event system.
  73. *
  74. * @var \Doctrine\Common\EventManager
  75. */
  76. private $eventManager;
  77. /**
  78. * The maintained (cached) hydrators. One instance per type.
  79. *
  80. * @var array
  81. */
  82. private $hydrators = array();
  83. /**
  84. * The proxy factory used to create dynamic proxies.
  85. *
  86. * @var \Doctrine\ORM\Proxy\ProxyFactory
  87. */
  88. private $proxyFactory;
  89. /**
  90. * The expression builder instance used to generate query expressions.
  91. *
  92. * @var \Doctrine\ORM\Query\Expr
  93. */
  94. private $expressionBuilder;
  95. /**
  96. * Whether the EntityManager is closed or not.
  97. *
  98. * @var bool
  99. */
  100. private $closed = false;
  101. /**
  102. * Collection of query filters.
  103. *
  104. * @var Doctrine\ORM\Query\FilterCollection
  105. */
  106. private $filterCollection;
  107. /**
  108. * Creates a new EntityManager that operates on the given database connection
  109. * and uses the given Configuration and EventManager implementations.
  110. *
  111. * @param \Doctrine\DBAL\Connection $conn
  112. * @param \Doctrine\ORM\Configuration $config
  113. * @param \Doctrine\Common\EventManager $eventManager
  114. */
  115. protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
  116. {
  117. $this->conn = $conn;
  118. $this->config = $config;
  119. $this->eventManager = $eventManager;
  120. $metadataFactoryClassName = $config->getClassMetadataFactoryName();
  121. $this->metadataFactory = new $metadataFactoryClassName;
  122. $this->metadataFactory->setEntityManager($this);
  123. $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl());
  124. $this->unitOfWork = new UnitOfWork($this);
  125. $this->proxyFactory = new ProxyFactory(
  126. $this,
  127. $config->getProxyDir(),
  128. $config->getProxyNamespace(),
  129. $config->getAutoGenerateProxyClasses()
  130. );
  131. }
  132. /**
  133. * Gets the database connection object used by the EntityManager.
  134. *
  135. * @return \Doctrine\DBAL\Connection
  136. */
  137. public function getConnection()
  138. {
  139. return $this->conn;
  140. }
  141. /**
  142. * Gets the metadata factory used to gather the metadata of classes.
  143. *
  144. * @return \Doctrine\ORM\Mapping\ClassMetadataFactory
  145. */
  146. public function getMetadataFactory()
  147. {
  148. return $this->metadataFactory;
  149. }
  150. /**
  151. * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
  152. *
  153. * Example:
  154. *
  155. * <code>
  156. * $qb = $em->createQueryBuilder();
  157. * $expr = $em->getExpressionBuilder();
  158. * $qb->select('u')->from('User', 'u')
  159. * ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2)));
  160. * </code>
  161. *
  162. * @return \Doctrine\ORM\Query\Expr
  163. */
  164. public function getExpressionBuilder()
  165. {
  166. if ($this->expressionBuilder === null) {
  167. $this->expressionBuilder = new Query\Expr;
  168. }
  169. return $this->expressionBuilder;
  170. }
  171. /**
  172. * Starts a transaction on the underlying database connection.
  173. */
  174. public function beginTransaction()
  175. {
  176. $this->conn->beginTransaction();
  177. }
  178. /**
  179. * Executes a function in a transaction.
  180. *
  181. * The function gets passed this EntityManager instance as an (optional) parameter.
  182. *
  183. * {@link flush} is invoked prior to transaction commit.
  184. *
  185. * If an exception occurs during execution of the function or flushing or transaction commit,
  186. * the transaction is rolled back, the EntityManager closed and the exception re-thrown.
  187. *
  188. * @param callable $func The function to execute transactionally.
  189. * @return mixed Returns the non-empty value returned from the closure or true instead
  190. */
  191. public function transactional($func)
  192. {
  193. if (!is_callable($func)) {
  194. throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
  195. }
  196. $this->conn->beginTransaction();
  197. try {
  198. $return = call_user_func($func, $this);
  199. $this->flush();
  200. $this->conn->commit();
  201. return $return ?: true;
  202. } catch (Exception $e) {
  203. $this->close();
  204. $this->conn->rollback();
  205. throw $e;
  206. }
  207. }
  208. /**
  209. * Commits a transaction on the underlying database connection.
  210. */
  211. public function commit()
  212. {
  213. $this->conn->commit();
  214. }
  215. /**
  216. * Performs a rollback on the underlying database connection.
  217. */
  218. public function rollback()
  219. {
  220. $this->conn->rollback();
  221. }
  222. /**
  223. * Returns the ORM metadata descriptor for a class.
  224. *
  225. * The class name must be the fully-qualified class name without a leading backslash
  226. * (as it is returned by get_class($obj)) or an aliased class name.
  227. *
  228. * Examples:
  229. * MyProject\Domain\User
  230. * sales:PriceRequest
  231. *
  232. * @return \Doctrine\ORM\Mapping\ClassMetadata
  233. * @internal Performance-sensitive method.
  234. */
  235. public function getClassMetadata($className)
  236. {
  237. return $this->metadataFactory->getMetadataFor($className);
  238. }
  239. /**
  240. * Creates a new Query object.
  241. *
  242. * @param string $dql The DQL string.
  243. * @return \Doctrine\ORM\Query
  244. */
  245. public function createQuery($dql = "")
  246. {
  247. $query = new Query($this);
  248. if ( ! empty($dql)) {
  249. $query->setDql($dql);
  250. }
  251. return $query;
  252. }
  253. /**
  254. * Creates a Query from a named query.
  255. *
  256. * @param string $name
  257. * @return \Doctrine\ORM\Query
  258. */
  259. public function createNamedQuery($name)
  260. {
  261. return $this->createQuery($this->config->getNamedQuery($name));
  262. }
  263. /**
  264. * Creates a native SQL query.
  265. *
  266. * @param string $sql
  267. * @param ResultSetMapping $rsm The ResultSetMapping to use.
  268. * @return NativeQuery
  269. */
  270. public function createNativeQuery($sql, ResultSetMapping $rsm)
  271. {
  272. $query = new NativeQuery($this);
  273. $query->setSql($sql);
  274. $query->setResultSetMapping($rsm);
  275. return $query;
  276. }
  277. /**
  278. * Creates a NativeQuery from a named native query.
  279. *
  280. * @param string $name
  281. * @return \Doctrine\ORM\NativeQuery
  282. */
  283. public function createNamedNativeQuery($name)
  284. {
  285. list($sql, $rsm) = $this->config->getNamedNativeQuery($name);
  286. return $this->createNativeQuery($sql, $rsm);
  287. }
  288. /**
  289. * Create a QueryBuilder instance
  290. *
  291. * @return QueryBuilder $qb
  292. */
  293. public function createQueryBuilder()
  294. {
  295. return new QueryBuilder($this);
  296. }
  297. /**
  298. * Flushes all changes to objects that have been queued up to now to the database.
  299. * This effectively synchronizes the in-memory state of managed objects with the
  300. * database.
  301. *
  302. * If an entity is explicitly passed to this method only this entity and
  303. * the cascade-persist semantics + scheduled inserts/removals are synchronized.
  304. *
  305. * @param object $entity
  306. * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
  307. * makes use of optimistic locking fails.
  308. */
  309. public function flush($entity = null)
  310. {
  311. $this->errorIfClosed();
  312. $this->unitOfWork->commit($entity);
  313. }
  314. /**
  315. * Finds an Entity by its identifier.
  316. *
  317. * @param string $entityName
  318. * @param mixed $id
  319. * @param integer $lockMode
  320. * @param integer $lockVersion
  321. *
  322. * @return object
  323. */
  324. public function find($entityName, $id, $lockMode = LockMode::NONE, $lockVersion = null)
  325. {
  326. $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
  327. if ( ! is_array($id)) {
  328. $id = array($class->identifier[0] => $id);
  329. }
  330. $sortedId = array();
  331. foreach ($class->identifier as $identifier) {
  332. if ( ! isset($id[$identifier])) {
  333. throw ORMException::missingIdentifierField($class->name, $identifier);
  334. }
  335. $sortedId[$identifier] = $id[$identifier];
  336. }
  337. $unitOfWork = $this->getUnitOfWork();
  338. // Check identity map first
  339. if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
  340. if ( ! ($entity instanceof $class->name)) {
  341. return null;
  342. }
  343. switch ($lockMode) {
  344. case LockMode::OPTIMISTIC:
  345. $this->lock($entity, $lockMode, $lockVersion);
  346. break;
  347. case LockMode::PESSIMISTIC_READ:
  348. case LockMode::PESSIMISTIC_WRITE:
  349. $persister = $unitOfWork->getEntityPersister($class->name);
  350. $persister->refresh($sortedId, $entity, $lockMode);
  351. break;
  352. }
  353. return $entity; // Hit!
  354. }
  355. $persister = $unitOfWork->getEntityPersister($class->name);
  356. switch ($lockMode) {
  357. case LockMode::NONE:
  358. return $persister->load($sortedId);
  359. case LockMode::OPTIMISTIC:
  360. if ( ! $class->isVersioned) {
  361. throw OptimisticLockException::notVersioned($class->name);
  362. }
  363. $entity = $persister->load($sortedId);
  364. $unitOfWork->lock($entity, $lockMode, $lockVersion);
  365. return $entity;
  366. default:
  367. if ( ! $this->getConnection()->isTransactionActive()) {
  368. throw TransactionRequiredException::transactionRequired();
  369. }
  370. return $persister->load($sortedId, null, null, array(), $lockMode);
  371. }
  372. }
  373. /**
  374. * Gets a reference to the entity identified by the given type and identifier
  375. * without actually loading it, if the entity is not yet loaded.
  376. *
  377. * @param string $entityName The name of the entity type.
  378. * @param mixed $id The entity identifier.
  379. * @return object The entity reference.
  380. */
  381. public function getReference($entityName, $id)
  382. {
  383. $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
  384. if ( ! is_array($id)) {
  385. $id = array($class->identifier[0] => $id);
  386. }
  387. $sortedId = array();
  388. foreach ($class->identifier as $identifier) {
  389. if ( ! isset($id[$identifier])) {
  390. throw ORMException::missingIdentifierField($class->name, $identifier);
  391. }
  392. $sortedId[$identifier] = $id[$identifier];
  393. }
  394. // Check identity map first, if its already in there just return it.
  395. if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
  396. return ($entity instanceof $class->name) ? $entity : null;
  397. }
  398. if ($class->subClasses) {
  399. return $this->find($entityName, $sortedId);
  400. }
  401. if ( ! is_array($sortedId)) {
  402. $sortedId = array($class->identifier[0] => $sortedId);
  403. }
  404. $entity = $this->proxyFactory->getProxy($class->name, $sortedId);
  405. $this->unitOfWork->registerManaged($entity, $sortedId, array());
  406. return $entity;
  407. }
  408. /**
  409. * Gets a partial reference to the entity identified by the given type and identifier
  410. * without actually loading it, if the entity is not yet loaded.
  411. *
  412. * The returned reference may be a partial object if the entity is not yet loaded/managed.
  413. * If it is a partial object it will not initialize the rest of the entity state on access.
  414. * Thus you can only ever safely access the identifier of an entity obtained through
  415. * this method.
  416. *
  417. * The use-cases for partial references involve maintaining bidirectional associations
  418. * without loading one side of the association or to update an entity without loading it.
  419. * Note, however, that in the latter case the original (persistent) entity data will
  420. * never be visible to the application (especially not event listeners) as it will
  421. * never be loaded in the first place.
  422. *
  423. * @param string $entityName The name of the entity type.
  424. * @param mixed $identifier The entity identifier.
  425. * @return object The (partial) entity reference.
  426. */
  427. public function getPartialReference($entityName, $identifier)
  428. {
  429. $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
  430. // Check identity map first, if its already in there just return it.
  431. if (($entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName)) !== false) {
  432. return ($entity instanceof $class->name) ? $entity : null;
  433. }
  434. if ( ! is_array($identifier)) {
  435. $identifier = array($class->identifier[0] => $identifier);
  436. }
  437. $entity = $class->newInstance();
  438. $class->setIdentifierValues($entity, $identifier);
  439. $this->unitOfWork->registerManaged($entity, $identifier, array());
  440. $this->unitOfWork->markReadOnly($entity);
  441. return $entity;
  442. }
  443. /**
  444. * Clears the EntityManager. All entities that are currently managed
  445. * by this EntityManager become detached.
  446. *
  447. * @param string $entityName if given, only entities of this type will get detached
  448. */
  449. public function clear($entityName = null)
  450. {
  451. $this->unitOfWork->clear($entityName);
  452. }
  453. /**
  454. * Closes the EntityManager. All entities that are currently managed
  455. * by this EntityManager become detached. The EntityManager may no longer
  456. * be used after it is closed.
  457. */
  458. public function close()
  459. {
  460. $this->clear();
  461. $this->closed = true;
  462. }
  463. /**
  464. * Tells the EntityManager to make an instance managed and persistent.
  465. *
  466. * The entity will be entered into the database at or before transaction
  467. * commit or as a result of the flush operation.
  468. *
  469. * NOTE: The persist operation always considers entities that are not yet known to
  470. * this EntityManager as NEW. Do not pass detached entities to the persist operation.
  471. *
  472. * @param object $object The instance to make managed and persistent.
  473. */
  474. public function persist($entity)
  475. {
  476. if ( ! is_object($entity)) {
  477. throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()' , $entity);
  478. }
  479. $this->errorIfClosed();
  480. $this->unitOfWork->persist($entity);
  481. }
  482. /**
  483. * Removes an entity instance.
  484. *
  485. * A removed entity will be removed from the database at or before transaction commit
  486. * or as a result of the flush operation.
  487. *
  488. * @param object $entity The entity instance to remove.
  489. */
  490. public function remove($entity)
  491. {
  492. if ( ! is_object($entity)) {
  493. throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()' , $entity);
  494. }
  495. $this->errorIfClosed();
  496. $this->unitOfWork->remove($entity);
  497. }
  498. /**
  499. * Refreshes the persistent state of an entity from the database,
  500. * overriding any local changes that have not yet been persisted.
  501. *
  502. * @param object $entity The entity to refresh.
  503. */
  504. public function refresh($entity)
  505. {
  506. if ( ! is_object($entity)) {
  507. throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()' , $entity);
  508. }
  509. $this->errorIfClosed();
  510. $this->unitOfWork->refresh($entity);
  511. }
  512. /**
  513. * Detaches an entity from the EntityManager, causing a managed entity to
  514. * become detached. Unflushed changes made to the entity if any
  515. * (including removal of the entity), will not be synchronized to the database.
  516. * Entities which previously referenced the detached entity will continue to
  517. * reference it.
  518. *
  519. * @param object $entity The entity to detach.
  520. */
  521. public function detach($entity)
  522. {
  523. if ( ! is_object($entity)) {
  524. throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()' , $entity);
  525. }
  526. $this->unitOfWork->detach($entity);
  527. }
  528. /**
  529. * Merges the state of a detached entity into the persistence context
  530. * of this EntityManager and returns the managed copy of the entity.
  531. * The entity passed to merge will not become associated/managed with this EntityManager.
  532. *
  533. * @param object $entity The detached entity to merge into the persistence context.
  534. * @return object The managed copy of the entity.
  535. */
  536. public function merge($entity)
  537. {
  538. if ( ! is_object($entity)) {
  539. throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()' , $entity);
  540. }
  541. $this->errorIfClosed();
  542. return $this->unitOfWork->merge($entity);
  543. }
  544. /**
  545. * Creates a copy of the given entity. Can create a shallow or a deep copy.
  546. *
  547. * @param object $entity The entity to copy.
  548. * @return object The new entity.
  549. * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e:
  550. * Fatal error: Maximum function nesting level of '100' reached, aborting!
  551. */
  552. public function copy($entity, $deep = false)
  553. {
  554. throw new \BadMethodCallException("Not implemented.");
  555. }
  556. /**
  557. * Acquire a lock on the given entity.
  558. *
  559. * @param object $entity
  560. * @param int $lockMode
  561. * @param int $lockVersion
  562. * @throws OptimisticLockException
  563. * @throws PessimisticLockException
  564. */
  565. public function lock($entity, $lockMode, $lockVersion = null)
  566. {
  567. $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
  568. }
  569. /**
  570. * Gets the repository for an entity class.
  571. *
  572. * @param string $entityName The name of the entity.
  573. * @return EntityRepository The repository class.
  574. */
  575. public function getRepository($entityName)
  576. {
  577. $entityName = ltrim($entityName, '\\');
  578. if (isset($this->repositories[$entityName])) {
  579. return $this->repositories[$entityName];
  580. }
  581. $metadata = $this->getClassMetadata($entityName);
  582. $repositoryClassName = $metadata->customRepositoryClassName;
  583. if ($repositoryClassName === null) {
  584. $repositoryClassName = $this->config->getDefaultRepositoryClassName();
  585. }
  586. $repository = new $repositoryClassName($this, $metadata);
  587. $this->repositories[$entityName] = $repository;
  588. return $repository;
  589. }
  590. /**
  591. * Determines whether an entity instance is managed in this EntityManager.
  592. *
  593. * @param object $entity
  594. * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
  595. */
  596. public function contains($entity)
  597. {
  598. return $this->unitOfWork->isScheduledForInsert($entity)
  599. || $this->unitOfWork->isInIdentityMap($entity)
  600. && ! $this->unitOfWork->isScheduledForDelete($entity);
  601. }
  602. /**
  603. * Gets the EventManager used by the EntityManager.
  604. *
  605. * @return \Doctrine\Common\EventManager
  606. */
  607. public function getEventManager()
  608. {
  609. return $this->eventManager;
  610. }
  611. /**
  612. * Gets the Configuration used by the EntityManager.
  613. *
  614. * @return \Doctrine\ORM\Configuration
  615. */
  616. public function getConfiguration()
  617. {
  618. return $this->config;
  619. }
  620. /**
  621. * Throws an exception if the EntityManager is closed or currently not active.
  622. *
  623. * @throws ORMException If the EntityManager is closed.
  624. */
  625. private function errorIfClosed()
  626. {
  627. if ($this->closed) {
  628. throw ORMException::entityManagerClosed();
  629. }
  630. }
  631. /**
  632. * Check if the Entity manager is open or closed.
  633. *
  634. * @return bool
  635. */
  636. public function isOpen()
  637. {
  638. return (!$this->closed);
  639. }
  640. /**
  641. * Gets the UnitOfWork used by the EntityManager to coordinate operations.
  642. *
  643. * @return \Doctrine\ORM\UnitOfWork
  644. */
  645. public function getUnitOfWork()
  646. {
  647. return $this->unitOfWork;
  648. }
  649. /**
  650. * Gets a hydrator for the given hydration mode.
  651. *
  652. * This method caches the hydrator instances which is used for all queries that don't
  653. * selectively iterate over the result.
  654. *
  655. * @param int $hydrationMode
  656. * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator
  657. */
  658. public function getHydrator($hydrationMode)
  659. {
  660. if ( ! isset($this->hydrators[$hydrationMode])) {
  661. $this->hydrators[$hydrationMode] = $this->newHydrator($hydrationMode);
  662. }
  663. return $this->hydrators[$hydrationMode];
  664. }
  665. /**
  666. * Create a new instance for the given hydration mode.
  667. *
  668. * @param int $hydrationMode
  669. * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator
  670. */
  671. public function newHydrator($hydrationMode)
  672. {
  673. switch ($hydrationMode) {
  674. case Query::HYDRATE_OBJECT:
  675. return new Internal\Hydration\ObjectHydrator($this);
  676. case Query::HYDRATE_ARRAY:
  677. return new Internal\Hydration\ArrayHydrator($this);
  678. case Query::HYDRATE_SCALAR:
  679. return new Internal\Hydration\ScalarHydrator($this);
  680. case Query::HYDRATE_SINGLE_SCALAR:
  681. return new Internal\Hydration\SingleScalarHydrator($this);
  682. case Query::HYDRATE_SIMPLEOBJECT:
  683. return new Internal\Hydration\SimpleObjectHydrator($this);
  684. default:
  685. if (($class = $this->config->getCustomHydrationMode($hydrationMode)) !== null) {
  686. return new $class($this);
  687. }
  688. }
  689. throw ORMException::invalidHydrationMode($hydrationMode);
  690. }
  691. /**
  692. * Gets the proxy factory used by the EntityManager to create entity proxies.
  693. *
  694. * @return ProxyFactory
  695. */
  696. public function getProxyFactory()
  697. {
  698. return $this->proxyFactory;
  699. }
  700. /**
  701. * Helper method to initialize a lazy loading proxy or persistent collection.
  702. *
  703. * This method is a no-op for other objects
  704. *
  705. * @param object $obj
  706. */
  707. public function initializeObject($obj)
  708. {
  709. $this->unitOfWork->initializeObject($obj);
  710. }
  711. /**
  712. * Factory method to create EntityManager instances.
  713. *
  714. * @param mixed $conn An array with the connection parameters or an existing
  715. * Connection instance.
  716. * @param Configuration $config The Configuration instance to use.
  717. * @param EventManager $eventManager The EventManager instance to use.
  718. * @return EntityManager The created EntityManager.
  719. */
  720. public static function create($conn, Configuration $config, EventManager $eventManager = null)
  721. {
  722. if ( ! $config->getMetadataDriverImpl()) {
  723. throw ORMException::missingMappingDriverImpl();
  724. }
  725. switch (true) {
  726. case (is_array($conn)):
  727. $conn = \Doctrine\DBAL\DriverManager::getConnection(
  728. $conn, $config, ($eventManager ?: new EventManager())
  729. );
  730. break;
  731. case ($conn instanceof Connection):
  732. if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
  733. throw ORMException::mismatchedEventManager();
  734. }
  735. break;
  736. default:
  737. throw new \InvalidArgumentException("Invalid argument: " . $conn);
  738. }
  739. return new EntityManager($conn, $config, $conn->getEventManager());
  740. }
  741. /**
  742. * Gets the enabled filters.
  743. *
  744. * @return FilterCollection The active filter collection.
  745. */
  746. public function getFilters()
  747. {
  748. if (null === $this->filterCollection) {
  749. $this->filterCollection = new FilterCollection($this);
  750. }
  751. return $this->filterCollection;
  752. }
  753. /**
  754. * Checks whether the state of the filter collection is clean.
  755. *
  756. * @return boolean True, if the filter collection is clean.
  757. */
  758. public function isFiltersStateClean()
  759. {
  760. return null === $this->filterCollection || $this->filterCollection->isClean();
  761. }
  762. /**
  763. * Checks whether the Entity Manager has filters.
  764. *
  765. * @return True, if the EM has a filter collection.
  766. */
  767. public function hasFilters()
  768. {
  769. return null !== $this->filterCollection;
  770. }
  771. }