ClassMetadataFactory.php 18KB

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