EntityManager.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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 LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM;
  20. use Closure, 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. * @deprecated Use {@link getConnection}.beginTransaction().
  175. */
  176. public function beginTransaction()
  177. {
  178. $this->conn->beginTransaction();
  179. }
  180. /**
  181. * Executes a function in a transaction.
  182. *
  183. * The function gets passed this EntityManager instance as an (optional) parameter.
  184. *
  185. * {@link flush} is invoked prior to transaction commit.
  186. *
  187. * If an exception occurs during execution of the function or flushing or transaction commit,
  188. * the transaction is rolled back, the EntityManager closed and the exception re-thrown.
  189. *
  190. * @param Closure $func The function to execute transactionally.
  191. * @return mixed Returns the non-empty value returned from the closure or true instead
  192. */
  193. public function transactional(Closure $func)
  194. {
  195. $this->conn->beginTransaction();
  196. try {
  197. $return = $func($this);
  198. $this->flush();
  199. $this->conn->commit();
  200. return $return ?: true;
  201. } catch (Exception $e) {
  202. $this->close();
  203. $this->conn->rollback();
  204. throw $e;
  205. }
  206. }
  207. /**
  208. * Commits a transaction on the underlying database connection.
  209. *
  210. * @deprecated Use {@link getConnection}.commit().
  211. */
  212. public function commit()
  213. {
  214. $this->conn->commit();
  215. }
  216. /**
  217. * Performs a rollback on the underlying database connection.
  218. *
  219. * @deprecated Use {@link getConnection}.rollback().
  220. */
  221. public function rollback()
  222. {
  223. $this->conn->rollback();
  224. }
  225. /**
  226. * Returns the ORM metadata descriptor for a class.
  227. *
  228. * The class name must be the fully-qualified class name without a leading backslash
  229. * (as it is returned by get_class($obj)) or an aliased class name.
  230. *
  231. * Examples:
  232. * MyProject\Domain\User
  233. * sales:PriceRequest
  234. *
  235. * @return \Doctrine\ORM\Mapping\ClassMetadata
  236. * @internal Performance-sensitive method.
  237. */
  238. public function getClassMetadata($className)
  239. {
  240. return $this->metadataFactory->getMetadataFor($className);
  241. }
  242. /**
  243. * Creates a new Query object.
  244. *
  245. * @param string The DQL string.
  246. * @return \Doctrine\ORM\Query
  247. */
  248. public function createQuery($dql = "")
  249. {
  250. $query = new Query($this);
  251. if ( ! empty($dql)) {
  252. $query->setDql($dql);
  253. }
  254. return $query;
  255. }
  256. /**
  257. * Creates a Query from a named query.
  258. *
  259. * @param string $name
  260. * @return \Doctrine\ORM\Query
  261. */
  262. public function createNamedQuery($name)
  263. {
  264. return $this->createQuery($this->config->getNamedQuery($name));
  265. }
  266. /**
  267. * Creates a native SQL query.
  268. *
  269. * @param string $sql
  270. * @param ResultSetMapping $rsm The ResultSetMapping to use.
  271. * @return NativeQuery
  272. */
  273. public function createNativeQuery($sql, ResultSetMapping $rsm)
  274. {
  275. $query = new NativeQuery($this);
  276. $query->setSql($sql);
  277. $query->setResultSetMapping($rsm);
  278. return $query;
  279. }
  280. /**
  281. * Creates a NativeQuery from a named native query.
  282. *
  283. * @param string $name
  284. * @return \Doctrine\ORM\NativeQuery
  285. */
  286. public function createNamedNativeQuery($name)
  287. {
  288. list($sql, $rsm) = $this->config->getNamedNativeQuery($name);
  289. return $this->createNativeQuery($sql, $rsm);
  290. }
  291. /**
  292. * Create a QueryBuilder instance
  293. *
  294. * @return QueryBuilder $qb
  295. */
  296. public function createQueryBuilder()
  297. {
  298. return new QueryBuilder($this);
  299. }
  300. /**
  301. * Flushes all changes to objects that have been queued up to now to the database.
  302. * This effectively synchronizes the in-memory state of managed objects with the
  303. * database.
  304. *
  305. * If an entity is explicitly passed to this method only this entity and
  306. * the cascade-persist semantics + scheduled inserts/removals are synchronized.
  307. *
  308. * @param object $entity
  309. * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
  310. * makes use of optimistic locking fails.
  311. */
  312. public function flush($entity = null)
  313. {
  314. $this->errorIfClosed();
  315. $this->unitOfWork->commit($entity);
  316. }
  317. /**
  318. * Finds an Entity by its identifier.
  319. *
  320. * This is just a convenient shortcut for getRepository($entityName)->find($id).
  321. *
  322. * @param string $entityName
  323. * @param mixed $identifier
  324. * @param int $lockMode
  325. * @param int $lockVersion
  326. * @return object
  327. */
  328. public function find($entityName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
  329. {
  330. return $this->getRepository($entityName)->find($identifier, $lockMode, $lockVersion);
  331. }
  332. /**
  333. * Gets a reference to the entity identified by the given type and identifier
  334. * without actually loading it, if the entity is not yet loaded.
  335. *
  336. * @param string $entityName The name of the entity type.
  337. * @param mixed $id The entity identifier.
  338. * @return object The entity reference.
  339. */
  340. public function getReference($entityName, $id)
  341. {
  342. $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
  343. if ( ! is_array($id)) {
  344. $id = array($class->identifier[0] => $id);
  345. }
  346. $sortedId = array();
  347. foreach ($class->identifier as $identifier) {
  348. if (!isset($id[$identifier])) {
  349. throw ORMException::missingIdentifierField($class->name, $identifier);
  350. }
  351. $sortedId[$identifier] = $id[$identifier];
  352. }
  353. // Check identity map first, if its already in there just return it.
  354. if ($entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName)) {
  355. return ($entity instanceof $class->name) ? $entity : null;
  356. }
  357. if ($class->subClasses) {
  358. return $this->find($entityName, $sortedId);
  359. }
  360. if ( ! is_array($sortedId)) {
  361. $sortedId = array($class->identifier[0] => $sortedId);
  362. }
  363. $entity = $this->proxyFactory->getProxy($class->name, $sortedId);
  364. $this->unitOfWork->registerManaged($entity, $sortedId, array());
  365. return $entity;
  366. }
  367. /**
  368. * Gets a partial reference to the entity identified by the given type and identifier
  369. * without actually loading it, if the entity is not yet loaded.
  370. *
  371. * The returned reference may be a partial object if the entity is not yet loaded/managed.
  372. * If it is a partial object it will not initialize the rest of the entity state on access.
  373. * Thus you can only ever safely access the identifier of an entity obtained through
  374. * this method.
  375. *
  376. * The use-cases for partial references involve maintaining bidirectional associations
  377. * without loading one side of the association or to update an entity without loading it.
  378. * Note, however, that in the latter case the original (persistent) entity data will
  379. * never be visible to the application (especially not event listeners) as it will
  380. * never be loaded in the first place.
  381. *
  382. * @param string $entityName The name of the entity type.
  383. * @param mixed $identifier The entity identifier.
  384. * @return object The (partial) entity reference.
  385. */
  386. public function getPartialReference($entityName, $identifier)
  387. {
  388. $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
  389. // Check identity map first, if its already in there just return it.
  390. if ($entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName)) {
  391. return ($entity instanceof $class->name) ? $entity : null;
  392. }
  393. if ( ! is_array($identifier)) {
  394. $identifier = array($class->identifier[0] => $identifier);
  395. }
  396. $entity = $class->newInstance();
  397. $class->setIdentifierValues($entity, $identifier);
  398. $this->unitOfWork->registerManaged($entity, $identifier, array());
  399. $this->unitOfWork->markReadOnly($entity);
  400. return $entity;
  401. }
  402. /**
  403. * Clears the EntityManager. All entities that are currently managed
  404. * by this EntityManager become detached.
  405. *
  406. * @param string $entityName if given, only entities of this type will get detached
  407. */
  408. public function clear($entityName = null)
  409. {
  410. $this->unitOfWork->clear($entityName);
  411. }
  412. /**
  413. * Closes the EntityManager. All entities that are currently managed
  414. * by this EntityManager become detached. The EntityManager may no longer
  415. * be used after it is closed.
  416. */
  417. public function close()
  418. {
  419. $this->clear();
  420. $this->closed = true;
  421. }
  422. /**
  423. * Tells the EntityManager to make an instance managed and persistent.
  424. *
  425. * The entity will be entered into the database at or before transaction
  426. * commit or as a result of the flush operation.
  427. *
  428. * NOTE: The persist operation always considers entities that are not yet known to
  429. * this EntityManager as NEW. Do not pass detached entities to the persist operation.
  430. *
  431. * @param object $object The instance to make managed and persistent.
  432. */
  433. public function persist($entity)
  434. {
  435. if ( ! is_object($entity)) {
  436. throw new \InvalidArgumentException(gettype($entity));
  437. }
  438. $this->errorIfClosed();
  439. $this->unitOfWork->persist($entity);
  440. }
  441. /**
  442. * Removes an entity instance.
  443. *
  444. * A removed entity will be removed from the database at or before transaction commit
  445. * or as a result of the flush operation.
  446. *
  447. * @param object $entity The entity instance to remove.
  448. */
  449. public function remove($entity)
  450. {
  451. if ( ! is_object($entity)) {
  452. throw new \InvalidArgumentException(gettype($entity));
  453. }
  454. $this->errorIfClosed();
  455. $this->unitOfWork->remove($entity);
  456. }
  457. /**
  458. * Refreshes the persistent state of an entity from the database,
  459. * overriding any local changes that have not yet been persisted.
  460. *
  461. * @param object $entity The entity to refresh.
  462. */
  463. public function refresh($entity)
  464. {
  465. if ( ! is_object($entity)) {
  466. throw new \InvalidArgumentException(gettype($entity));
  467. }
  468. $this->errorIfClosed();
  469. $this->unitOfWork->refresh($entity);
  470. }
  471. /**
  472. * Detaches an entity from the EntityManager, causing a managed entity to
  473. * become detached. Unflushed changes made to the entity if any
  474. * (including removal of the entity), will not be synchronized to the database.
  475. * Entities which previously referenced the detached entity will continue to
  476. * reference it.
  477. *
  478. * @param object $entity The entity to detach.
  479. */
  480. public function detach($entity)
  481. {
  482. if ( ! is_object($entity)) {
  483. throw new \InvalidArgumentException(gettype($entity));
  484. }
  485. $this->unitOfWork->detach($entity);
  486. }
  487. /**
  488. * Merges the state of a detached entity into the persistence context
  489. * of this EntityManager and returns the managed copy of the entity.
  490. * The entity passed to merge will not become associated/managed with this EntityManager.
  491. *
  492. * @param object $entity The detached entity to merge into the persistence context.
  493. * @return object The managed copy of the entity.
  494. */
  495. public function merge($entity)
  496. {
  497. if ( ! is_object($entity)) {
  498. throw new \InvalidArgumentException(gettype($entity));
  499. }
  500. $this->errorIfClosed();
  501. return $this->unitOfWork->merge($entity);
  502. }
  503. /**
  504. * Creates a copy of the given entity. Can create a shallow or a deep copy.
  505. *
  506. * @param object $entity The entity to copy.
  507. * @return object The new entity.
  508. * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e:
  509. * Fatal error: Maximum function nesting level of '100' reached, aborting!
  510. */
  511. public function copy($entity, $deep = false)
  512. {
  513. throw new \BadMethodCallException("Not implemented.");
  514. }
  515. /**
  516. * Acquire a lock on the given entity.
  517. *
  518. * @param object $entity
  519. * @param int $lockMode
  520. * @param int $lockVersion
  521. * @throws OptimisticLockException
  522. * @throws PessimisticLockException
  523. */
  524. public function lock($entity, $lockMode, $lockVersion = null)
  525. {
  526. $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
  527. }
  528. /**
  529. * Gets the repository for an entity class.
  530. *
  531. * @param string $entityName The name of the entity.
  532. * @return EntityRepository The repository class.
  533. */
  534. public function getRepository($entityName)
  535. {
  536. $entityName = ltrim($entityName, '\\');
  537. if (isset($this->repositories[$entityName])) {
  538. return $this->repositories[$entityName];
  539. }
  540. $metadata = $this->getClassMetadata($entityName);
  541. $repositoryClassName = $metadata->customRepositoryClassName;
  542. if ($repositoryClassName === null) {
  543. $repositoryClassName = $this->config->getDefaultRepositoryClassName();
  544. }
  545. $repository = new $repositoryClassName($this, $metadata);
  546. $this->repositories[$entityName] = $repository;
  547. return $repository;
  548. }
  549. /**
  550. * Determines whether an entity instance is managed in this EntityManager.
  551. *
  552. * @param object $entity
  553. * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
  554. */
  555. public function contains($entity)
  556. {
  557. return $this->unitOfWork->isScheduledForInsert($entity)
  558. || $this->unitOfWork->isInIdentityMap($entity)
  559. && ! $this->unitOfWork->isScheduledForDelete($entity);
  560. }
  561. /**
  562. * Gets the EventManager used by the EntityManager.
  563. *
  564. * @return \Doctrine\Common\EventManager
  565. */
  566. public function getEventManager()
  567. {
  568. return $this->eventManager;
  569. }
  570. /**
  571. * Gets the Configuration used by the EntityManager.
  572. *
  573. * @return \Doctrine\ORM\Configuration
  574. */
  575. public function getConfiguration()
  576. {
  577. return $this->config;
  578. }
  579. /**
  580. * Throws an exception if the EntityManager is closed or currently not active.
  581. *
  582. * @throws ORMException If the EntityManager is closed.
  583. */
  584. private function errorIfClosed()
  585. {
  586. if ($this->closed) {
  587. throw ORMException::entityManagerClosed();
  588. }
  589. }
  590. /**
  591. * Check if the Entity manager is open or closed.
  592. *
  593. * @return bool
  594. */
  595. public function isOpen()
  596. {
  597. return (!$this->closed);
  598. }
  599. /**
  600. * Gets the UnitOfWork used by the EntityManager to coordinate operations.
  601. *
  602. * @return \Doctrine\ORM\UnitOfWork
  603. */
  604. public function getUnitOfWork()
  605. {
  606. return $this->unitOfWork;
  607. }
  608. /**
  609. * Gets a hydrator for the given hydration mode.
  610. *
  611. * This method caches the hydrator instances which is used for all queries that don't
  612. * selectively iterate over the result.
  613. *
  614. * @param int $hydrationMode
  615. * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator
  616. */
  617. public function getHydrator($hydrationMode)
  618. {
  619. if ( ! isset($this->hydrators[$hydrationMode])) {
  620. $this->hydrators[$hydrationMode] = $this->newHydrator($hydrationMode);
  621. }
  622. return $this->hydrators[$hydrationMode];
  623. }
  624. /**
  625. * Create a new instance for the given hydration mode.
  626. *
  627. * @param int $hydrationMode
  628. * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator
  629. */
  630. public function newHydrator($hydrationMode)
  631. {
  632. switch ($hydrationMode) {
  633. case Query::HYDRATE_OBJECT:
  634. return new Internal\Hydration\ObjectHydrator($this);
  635. case Query::HYDRATE_ARRAY:
  636. return new Internal\Hydration\ArrayHydrator($this);
  637. case Query::HYDRATE_SCALAR:
  638. return new Internal\Hydration\ScalarHydrator($this);
  639. case Query::HYDRATE_SINGLE_SCALAR:
  640. return new Internal\Hydration\SingleScalarHydrator($this);
  641. case Query::HYDRATE_SIMPLEOBJECT:
  642. return new Internal\Hydration\SimpleObjectHydrator($this);
  643. default:
  644. if ($class = $this->config->getCustomHydrationMode($hydrationMode)) {
  645. return new $class($this);
  646. }
  647. }
  648. throw ORMException::invalidHydrationMode($hydrationMode);
  649. }
  650. /**
  651. * Gets the proxy factory used by the EntityManager to create entity proxies.
  652. *
  653. * @return ProxyFactory
  654. */
  655. public function getProxyFactory()
  656. {
  657. return $this->proxyFactory;
  658. }
  659. /**
  660. * Helper method to initialize a lazy loading proxy or persistent collection.
  661. *
  662. * This method is a no-op for other objects
  663. *
  664. * @param object $obj
  665. */
  666. public function initializeObject($obj)
  667. {
  668. $this->unitOfWork->initializeObject($obj);
  669. }
  670. /**
  671. * Factory method to create EntityManager instances.
  672. *
  673. * @param mixed $conn An array with the connection parameters or an existing
  674. * Connection instance.
  675. * @param Configuration $config The Configuration instance to use.
  676. * @param EventManager $eventManager The EventManager instance to use.
  677. * @return EntityManager The created EntityManager.
  678. */
  679. public static function create($conn, Configuration $config, EventManager $eventManager = null)
  680. {
  681. if ( ! $config->getMetadataDriverImpl()) {
  682. throw ORMException::missingMappingDriverImpl();
  683. }
  684. switch (true) {
  685. case (is_array($conn)):
  686. $conn = \Doctrine\DBAL\DriverManager::getConnection(
  687. $conn, $config, ($eventManager ?: new EventManager())
  688. );
  689. break;
  690. case ($conn instanceof Connection):
  691. if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
  692. throw ORMException::mismatchedEventManager();
  693. }
  694. break;
  695. default:
  696. throw new \InvalidArgumentException("Invalid argument: " . $conn);
  697. }
  698. return new EntityManager($conn, $config, $conn->getEventManager());
  699. }
  700. /**
  701. * Gets the enabled filters.
  702. *
  703. * @return FilterCollection The active filter collection.
  704. */
  705. public function getFilters()
  706. {
  707. if (null === $this->filterCollection) {
  708. $this->filterCollection = new FilterCollection($this);
  709. }
  710. return $this->filterCollection;
  711. }
  712. /**
  713. * Checks whether the state of the filter collection is clean.
  714. *
  715. * @return boolean True, if the filter collection is clean.
  716. */
  717. public function isFiltersStateClean()
  718. {
  719. return null === $this->filterCollection
  720. || $this->filterCollection->isClean();
  721. }
  722. /**
  723. * Checks whether the Entity Manager has filters.
  724. *
  725. * @return True, if the EM has a filter collection.
  726. */
  727. public function hasFilters()
  728. {
  729. return null !== $this->filterCollection;
  730. }
  731. }