ClassMetadataFactory.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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\Mapping;
  20. use ReflectionException,
  21. Doctrine\ORM\ORMException,
  22. Doctrine\ORM\EntityManager,
  23. Doctrine\DBAL\Platforms,
  24. Doctrine\ORM\Events,
  25. Doctrine\Common\Persistence\Mapping\RuntimeReflectionService,
  26. Doctrine\Common\Persistence\Mapping\ReflectionService,
  27. Doctrine\Common\Persistence\Mapping\ClassMetadataFactory as ClassMetadataFactoryInterface;
  28. /**
  29. * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
  30. * metadata mapping informations of a class which describes how a class should be mapped
  31. * to a relational database.
  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 ClassMetadataFactory implements ClassMetadataFactoryInterface
  40. {
  41. /**
  42. * @var EntityManager
  43. */
  44. private $em;
  45. /**
  46. * @var AbstractPlatform
  47. */
  48. private $targetPlatform;
  49. /**
  50. * @var \Doctrine\ORM\Mapping\Driver\Driver
  51. */
  52. private $driver;
  53. /**
  54. * @var \Doctrine\Common\EventManager
  55. */
  56. private $evm;
  57. /**
  58. * @var \Doctrine\Common\Cache\Cache
  59. */
  60. private $cacheDriver;
  61. /**
  62. * @var array
  63. */
  64. private $loadedMetadata = array();
  65. /**
  66. * @var bool
  67. */
  68. private $initialized = false;
  69. /**
  70. * @var ReflectionService
  71. */
  72. private $reflectionService;
  73. /**
  74. * @param EntityManager $$em
  75. */
  76. public function setEntityManager(EntityManager $em)
  77. {
  78. $this->em = $em;
  79. }
  80. /**
  81. * Sets the cache driver used by the factory to cache ClassMetadata instances.
  82. *
  83. * @param \Doctrine\Common\Cache\Cache $cacheDriver
  84. */
  85. public function setCacheDriver($cacheDriver)
  86. {
  87. $this->cacheDriver = $cacheDriver;
  88. }
  89. /**
  90. * Gets the cache driver used by the factory to cache ClassMetadata instances.
  91. *
  92. * @return \Doctrine\Common\Cache\Cache
  93. */
  94. public function getCacheDriver()
  95. {
  96. return $this->cacheDriver;
  97. }
  98. public function getLoadedMetadata()
  99. {
  100. return $this->loadedMetadata;
  101. }
  102. /**
  103. * Forces the factory to load the metadata of all classes known to the underlying
  104. * mapping driver.
  105. *
  106. * @return array The ClassMetadata instances of all mapped classes.
  107. */
  108. public function getAllMetadata()
  109. {
  110. if ( ! $this->initialized) {
  111. $this->initialize();
  112. }
  113. $metadata = array();
  114. foreach ($this->driver->getAllClassNames() as $className) {
  115. $metadata[] = $this->getMetadataFor($className);
  116. }
  117. return $metadata;
  118. }
  119. /**
  120. * Lazy initialization of this stuff, especially the metadata driver,
  121. * since these are not needed at all when a metadata cache is active.
  122. */
  123. private function initialize()
  124. {
  125. $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl();
  126. $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform();
  127. $this->evm = $this->em->getEventManager();
  128. $this->initialized = true;
  129. }
  130. /**
  131. * Gets the class metadata descriptor for a class.
  132. *
  133. * @param string $className The name of the class.
  134. * @return \Doctrine\ORM\Mapping\ClassMetadata
  135. */
  136. public function getMetadataFor($className)
  137. {
  138. if ( ! isset($this->loadedMetadata[$className])) {
  139. $realClassName = $className;
  140. // Check for namespace alias
  141. if (strpos($className, ':') !== false) {
  142. list($namespaceAlias, $simpleClassName) = explode(':', $className);
  143. $realClassName = $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName;
  144. if (isset($this->loadedMetadata[$realClassName])) {
  145. // We do not have the alias name in the map, include it
  146. $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
  147. return $this->loadedMetadata[$realClassName];
  148. }
  149. }
  150. if ($this->cacheDriver) {
  151. if (($cached = $this->cacheDriver->fetch("$realClassName\$CLASSMETADATA")) !== false) {
  152. $this->wakeupReflection($cached, $this->getReflectionService());
  153. $this->loadedMetadata[$realClassName] = $cached;
  154. } else {
  155. foreach ($this->loadMetadata($realClassName) as $loadedClassName) {
  156. $this->cacheDriver->save(
  157. "$loadedClassName\$CLASSMETADATA", $this->loadedMetadata[$loadedClassName], null
  158. );
  159. }
  160. }
  161. } else {
  162. $this->loadMetadata($realClassName);
  163. }
  164. if ($className != $realClassName) {
  165. // We do not have the alias name in the map, include it
  166. $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
  167. }
  168. }
  169. return $this->loadedMetadata[$className];
  170. }
  171. /**
  172. * Checks whether the factory has the metadata for a class loaded already.
  173. *
  174. * @param string $className
  175. * @return boolean TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
  176. */
  177. public function hasMetadataFor($className)
  178. {
  179. return isset($this->loadedMetadata[$className]);
  180. }
  181. /**
  182. * Sets the metadata descriptor for a specific class.
  183. *
  184. * NOTE: This is only useful in very special cases, like when generating proxy classes.
  185. *
  186. * @param string $className
  187. * @param ClassMetadata $class
  188. */
  189. public function setMetadataFor($className, $class)
  190. {
  191. $this->loadedMetadata[$className] = $class;
  192. }
  193. /**
  194. * Get array of parent classes for the given entity class
  195. *
  196. * @param string $name
  197. * @return array $parentClasses
  198. */
  199. protected function getParentClasses($name)
  200. {
  201. // Collect parent classes, ignoring transient (not-mapped) classes.
  202. $parentClasses = array();
  203. foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) {
  204. if ( ! $this->driver->isTransient($parentClass)) {
  205. $parentClasses[] = $parentClass;
  206. }
  207. }
  208. return $parentClasses;
  209. }
  210. /**
  211. * Loads the metadata of the class in question and all it's ancestors whose metadata
  212. * is still not loaded.
  213. *
  214. * @param string $name The name of the class for which the metadata should get loaded.
  215. * @param array $tables The metadata collection to which the loaded metadata is added.
  216. */
  217. protected function loadMetadata($name)
  218. {
  219. if ( ! $this->initialized) {
  220. $this->initialize();
  221. }
  222. $loaded = array();
  223. $parentClasses = $this->getParentClasses($name);
  224. $parentClasses[] = $name;
  225. // Move down the hierarchy of parent classes, starting from the topmost class
  226. $parent = null;
  227. $rootEntityFound = false;
  228. $visited = array();
  229. foreach ($parentClasses as $className) {
  230. if (isset($this->loadedMetadata[$className])) {
  231. $parent = $this->loadedMetadata[$className];
  232. if ( ! $parent->isMappedSuperclass) {
  233. $rootEntityFound = true;
  234. array_unshift($visited, $className);
  235. }
  236. continue;
  237. }
  238. $class = $this->newClassMetadataInstance($className);
  239. $this->initializeReflection($class, $this->getReflectionService());
  240. if ($parent) {
  241. $class->setInheritanceType($parent->inheritanceType);
  242. $class->setDiscriminatorColumn($parent->discriminatorColumn);
  243. $class->setIdGeneratorType($parent->generatorType);
  244. $this->addInheritedFields($class, $parent);
  245. $this->addInheritedRelations($class, $parent);
  246. $class->setIdentifier($parent->identifier);
  247. $class->setVersioned($parent->isVersioned);
  248. $class->setVersionField($parent->versionField);
  249. $class->setDiscriminatorMap($parent->discriminatorMap);
  250. $class->setLifecycleCallbacks($parent->lifecycleCallbacks);
  251. $class->setChangeTrackingPolicy($parent->changeTrackingPolicy);
  252. if ($parent->isMappedSuperclass) {
  253. $class->setCustomRepositoryClass($parent->customRepositoryClassName);
  254. }
  255. }
  256. // Invoke driver
  257. try {
  258. $this->driver->loadMetadataForClass($className, $class);
  259. } catch (ReflectionException $e) {
  260. throw MappingException::reflectionFailure($className, $e);
  261. }
  262. // If this class has a parent the id generator strategy is inherited.
  263. // However this is only true if the hierachy of parents contains the root entity,
  264. // if it consinsts of mapped superclasses these don't necessarily include the id field.
  265. if ($parent && $rootEntityFound) {
  266. if ($parent->isIdGeneratorSequence()) {
  267. $class->setSequenceGeneratorDefinition($parent->sequenceGeneratorDefinition);
  268. } else if ($parent->isIdGeneratorTable()) {
  269. $class->getTableGeneratorDefinition($parent->tableGeneratorDefinition);
  270. }
  271. if ($parent->generatorType) {
  272. $class->setIdGeneratorType($parent->generatorType);
  273. }
  274. if ($parent->idGenerator) {
  275. $class->setIdGenerator($parent->idGenerator);
  276. }
  277. } else {
  278. $this->completeIdGeneratorMapping($class);
  279. }
  280. if ($parent && $parent->isInheritanceTypeSingleTable()) {
  281. $class->setPrimaryTable($parent->table);
  282. }
  283. if ($parent && $parent->containsForeignIdentifier) {
  284. $class->containsForeignIdentifier = true;
  285. }
  286. if ($parent && !empty ($parent->namedQueries)) {
  287. $this->addInheritedNamedQueries($class, $parent);
  288. }
  289. $class->setParentClasses($visited);
  290. if ($this->evm->hasListeners(Events::loadClassMetadata)) {
  291. $eventArgs = new \Doctrine\ORM\Event\LoadClassMetadataEventArgs($class, $this->em);
  292. $this->evm->dispatchEvent(Events::loadClassMetadata, $eventArgs);
  293. }
  294. $this->wakeupReflection($class, $this->getReflectionService());
  295. $this->validateRuntimeMetadata($class, $parent);
  296. $this->loadedMetadata[$className] = $class;
  297. $parent = $class;
  298. if ( ! $class->isMappedSuperclass) {
  299. $rootEntityFound = true;
  300. array_unshift($visited, $className);
  301. }
  302. $loaded[] = $className;
  303. }
  304. return $loaded;
  305. }
  306. /**
  307. * Validate runtime metadata is correctly defined.
  308. *
  309. * @param ClassMetadata $class
  310. * @param ClassMetadata $parent
  311. */
  312. protected function validateRuntimeMetadata($class, $parent)
  313. {
  314. if ( ! $class->reflClass ) {
  315. // only validate if there is a reflection class instance
  316. return;
  317. }
  318. $class->validateIdentifier();
  319. $class->validateAssocations();
  320. $class->validateLifecycleCallbacks($this->getReflectionService());
  321. // verify inheritance
  322. if (!$class->isMappedSuperclass && !$class->isInheritanceTypeNone()) {
  323. if (!$parent) {
  324. if (count($class->discriminatorMap) == 0) {
  325. throw MappingException::missingDiscriminatorMap($class->name);
  326. }
  327. if (!$class->discriminatorColumn) {
  328. throw MappingException::missingDiscriminatorColumn($class->name);
  329. }
  330. } else if ($parent && !$class->reflClass->isAbstract() && !in_array($class->name, array_values($class->discriminatorMap))) {
  331. // enforce discriminator map for all entities of an inheritance hierachy, otherwise problems will occur.
  332. throw MappingException::mappedClassNotPartOfDiscriminatorMap($class->name, $class->rootEntityName);
  333. }
  334. } else if ($class->isMappedSuperclass && $class->name == $class->rootEntityName && (count($class->discriminatorMap) || $class->discriminatorColumn)) {
  335. // second condition is necessary for mapped superclasses in the middle of an inheritance hierachy
  336. throw MappingException::noInheritanceOnMappedSuperClass($class->name);
  337. }
  338. }
  339. /**
  340. * Creates a new ClassMetadata instance for the given class name.
  341. *
  342. * @param string $className
  343. * @return \Doctrine\ORM\Mapping\ClassMetadata
  344. */
  345. protected function newClassMetadataInstance($className)
  346. {
  347. return new ClassMetadata($className);
  348. }
  349. /**
  350. * Adds inherited fields to the subclass mapping.
  351. *
  352. * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
  353. * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
  354. */
  355. private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $parentClass)
  356. {
  357. foreach ($parentClass->fieldMappings as $fieldName => $mapping) {
  358. if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
  359. $mapping['inherited'] = $parentClass->name;
  360. }
  361. if ( ! isset($mapping['declared'])) {
  362. $mapping['declared'] = $parentClass->name;
  363. }
  364. $subClass->addInheritedFieldMapping($mapping);
  365. }
  366. foreach ($parentClass->reflFields as $name => $field) {
  367. $subClass->reflFields[$name] = $field;
  368. }
  369. }
  370. /**
  371. * Adds inherited association mappings to the subclass mapping.
  372. *
  373. * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
  374. * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
  375. */
  376. private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $parentClass)
  377. {
  378. foreach ($parentClass->associationMappings as $field => $mapping) {
  379. if ($parentClass->isMappedSuperclass) {
  380. if ($mapping['type'] & ClassMetadata::TO_MANY && !$mapping['isOwningSide']) {
  381. throw MappingException::illegalToManyAssocationOnMappedSuperclass($parentClass->name, $field);
  382. }
  383. $mapping['sourceEntity'] = $subClass->name;
  384. }
  385. //$subclassMapping = $mapping;
  386. if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
  387. $mapping['inherited'] = $parentClass->name;
  388. }
  389. if ( ! isset($mapping['declared'])) {
  390. $mapping['declared'] = $parentClass->name;
  391. }
  392. $subClass->addInheritedAssociationMapping($mapping);
  393. }
  394. }
  395. /**
  396. * Adds inherited named queries to the subclass mapping.
  397. *
  398. * @since 2.2
  399. * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
  400. * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
  401. */
  402. private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata $parentClass)
  403. {
  404. foreach ($parentClass->namedQueries as $name => $query) {
  405. if (!isset ($subClass->namedQueries[$name])) {
  406. $subClass->addNamedQuery(array(
  407. 'name' => $query['name'],
  408. 'query' => $query['query']
  409. ));
  410. }
  411. }
  412. }
  413. /**
  414. * Completes the ID generator mapping. If "auto" is specified we choose the generator
  415. * most appropriate for the targeted database platform.
  416. *
  417. * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  418. */
  419. private function completeIdGeneratorMapping(ClassMetadataInfo $class)
  420. {
  421. $idGenType = $class->generatorType;
  422. if ($idGenType == ClassMetadata::GENERATOR_TYPE_AUTO) {
  423. if ($this->targetPlatform->prefersSequences()) {
  424. $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_SEQUENCE);
  425. } else if ($this->targetPlatform->prefersIdentityColumns()) {
  426. $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
  427. } else {
  428. $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_TABLE);
  429. }
  430. }
  431. // Create & assign an appropriate ID generator instance
  432. switch ($class->generatorType) {
  433. case ClassMetadata::GENERATOR_TYPE_IDENTITY:
  434. // For PostgreSQL IDENTITY (SERIAL) we need a sequence name. It defaults to
  435. // <table>_<column>_seq in PostgreSQL for SERIAL columns.
  436. // Not pretty but necessary and the simplest solution that currently works.
  437. $seqName = $this->targetPlatform instanceof Platforms\PostgreSQLPlatform ?
  438. $class->getTableName() . '_' . $class->columnNames[$class->identifier[0]] . '_seq' :
  439. null;
  440. $class->setIdGenerator(new \Doctrine\ORM\Id\IdentityGenerator($seqName));
  441. break;
  442. case ClassMetadata::GENERATOR_TYPE_SEQUENCE:
  443. // If there is no sequence definition yet, create a default definition
  444. $definition = $class->sequenceGeneratorDefinition;
  445. if ( ! $definition) {
  446. $sequenceName = $class->getTableName() . '_' . $class->getSingleIdentifierColumnName() . '_seq';
  447. $definition['sequenceName'] = $this->targetPlatform->fixSchemaElementName($sequenceName);
  448. $definition['allocationSize'] = 1;
  449. $definition['initialValue'] = 1;
  450. $class->setSequenceGeneratorDefinition($definition);
  451. }
  452. $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator(
  453. $definition['sequenceName'],
  454. $definition['allocationSize']
  455. );
  456. $class->setIdGenerator($sequenceGenerator);
  457. break;
  458. case ClassMetadata::GENERATOR_TYPE_NONE:
  459. $class->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
  460. break;
  461. case ClassMetadata::GENERATOR_TYPE_TABLE:
  462. throw new ORMException("TableGenerator not yet implemented.");
  463. break;
  464. default:
  465. throw new ORMException("Unknown generator type: " . $class->generatorType);
  466. }
  467. }
  468. /**
  469. * Check if this class is mapped by this EntityManager + ClassMetadata configuration
  470. *
  471. * @param $class
  472. * @return bool
  473. */
  474. public function isTransient($class)
  475. {
  476. if ( ! $this->initialized) {
  477. $this->initialize();
  478. }
  479. // Check for namespace alias
  480. if (strpos($class, ':') !== false) {
  481. list($namespaceAlias, $simpleClassName) = explode(':', $class);
  482. $class = $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName;
  483. }
  484. return $this->driver->isTransient($class);
  485. }
  486. /**
  487. * Get reflectionService.
  488. *
  489. * @return \Doctrine\Common\Persistence\Mapping\ReflectionService
  490. */
  491. public function getReflectionService()
  492. {
  493. if ($this->reflectionService === null) {
  494. $this->reflectionService = new RuntimeReflectionService();
  495. }
  496. return $this->reflectionService;
  497. }
  498. /**
  499. * Set reflectionService.
  500. *
  501. * @param reflectionService the value to set.
  502. */
  503. public function setReflectionService(ReflectionService $reflectionService)
  504. {
  505. $this->reflectionService = $reflectionService;
  506. }
  507. /**
  508. * Wakeup reflection after ClassMetadata gets unserialized from cache.
  509. *
  510. * @param ClassMetadataInfo $class
  511. * @param ReflectionService $reflService
  512. * @return void
  513. */
  514. protected function wakeupReflection(ClassMetadataInfo $class, ReflectionService $reflService)
  515. {
  516. $class->wakeupReflection($reflService);
  517. }
  518. /**
  519. * Initialize Reflection after ClassMetadata was constructed.
  520. *
  521. * @param ClassMetadataInfo $class
  522. * @param ReflectionService $reflService
  523. * @return void
  524. */
  525. protected function initializeReflection(ClassMetadataInfo $class, ReflectionService $reflService)
  526. {
  527. $class->initializeReflection($reflService);
  528. }
  529. }