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