ClassMetadataFactory.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. $class->setParentClasses($visited);
  273. if ($this->evm->hasListeners(Events::loadClassMetadata)) {
  274. $eventArgs = new \Doctrine\ORM\Event\LoadClassMetadataEventArgs($class, $this->em);
  275. $this->evm->dispatchEvent(Events::loadClassMetadata, $eventArgs);
  276. }
  277. $this->validateRuntimeMetadata($class, $parent);
  278. $this->loadedMetadata[$className] = $class;
  279. $parent = $class;
  280. if ( ! $class->isMappedSuperclass) {
  281. $rootEntityFound = true;
  282. array_unshift($visited, $className);
  283. }
  284. $loaded[] = $className;
  285. }
  286. return $loaded;
  287. }
  288. /**
  289. * Validate runtime metadata is correctly defined.
  290. *
  291. * @param ClassMetadata $class
  292. * @param ClassMetadata $parent
  293. */
  294. protected function validateRuntimeMetadata($class, $parent)
  295. {
  296. // Verify & complete identifier mapping
  297. if ( ! $class->identifier && ! $class->isMappedSuperclass) {
  298. throw MappingException::identifierRequired($className);
  299. }
  300. // verify inheritance
  301. if (!$class->isMappedSuperclass && !$class->isInheritanceTypeNone()) {
  302. if (!$parent) {
  303. if (count($class->discriminatorMap) == 0) {
  304. throw MappingException::missingDiscriminatorMap($class->name);
  305. }
  306. if (!$class->discriminatorColumn) {
  307. throw MappingException::missingDiscriminatorColumn($class->name);
  308. }
  309. } else if ($parent && !$class->reflClass->isAbstract() && !in_array($class->name, array_values($class->discriminatorMap))) {
  310. // enforce discriminator map for all entities of an inheritance hierachy, otherwise problems will occur.
  311. throw MappingException::mappedClassNotPartOfDiscriminatorMap($class->name, $class->rootEntityName);
  312. }
  313. } else if ($class->isMappedSuperclass && $class->name == $class->rootEntityName && (count($class->discriminatorMap) || $class->discriminatorColumn)) {
  314. // second condition is necessary for mapped superclasses in the middle of an inheritance hierachy
  315. throw MappingException::noInheritanceOnMappedSuperClass($class->name);
  316. }
  317. }
  318. /**
  319. * Creates a new ClassMetadata instance for the given class name.
  320. *
  321. * @param string $className
  322. * @return Doctrine\ORM\Mapping\ClassMetadata
  323. */
  324. protected function newClassMetadataInstance($className)
  325. {
  326. return new ClassMetadata($className);
  327. }
  328. /**
  329. * Adds inherited fields to the subclass mapping.
  330. *
  331. * @param Doctrine\ORM\Mapping\ClassMetadata $subClass
  332. * @param Doctrine\ORM\Mapping\ClassMetadata $parentClass
  333. */
  334. private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $parentClass)
  335. {
  336. foreach ($parentClass->fieldMappings as $fieldName => $mapping) {
  337. if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
  338. $mapping['inherited'] = $parentClass->name;
  339. }
  340. if ( ! isset($mapping['declared'])) {
  341. $mapping['declared'] = $parentClass->name;
  342. }
  343. $subClass->addInheritedFieldMapping($mapping);
  344. }
  345. foreach ($parentClass->reflFields as $name => $field) {
  346. $subClass->reflFields[$name] = $field;
  347. }
  348. }
  349. /**
  350. * Adds inherited association mappings to the subclass mapping.
  351. *
  352. * @param Doctrine\ORM\Mapping\ClassMetadata $subClass
  353. * @param Doctrine\ORM\Mapping\ClassMetadata $parentClass
  354. */
  355. private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $parentClass)
  356. {
  357. foreach ($parentClass->associationMappings as $field => $mapping) {
  358. if ($parentClass->isMappedSuperclass) {
  359. if ($mapping['type'] & ClassMetadata::TO_MANY && !$mapping['isOwningSide']) {
  360. throw MappingException::illegalToManyAssocationOnMappedSuperclass($parentClass->name, $field);
  361. }
  362. $mapping['sourceEntity'] = $subClass->name;
  363. }
  364. //$subclassMapping = $mapping;
  365. if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
  366. $mapping['inherited'] = $parentClass->name;
  367. }
  368. if ( ! isset($mapping['declared'])) {
  369. $mapping['declared'] = $parentClass->name;
  370. }
  371. $subClass->addInheritedAssociationMapping($mapping);
  372. }
  373. }
  374. /**
  375. * Completes the ID generator mapping. If "auto" is specified we choose the generator
  376. * most appropriate for the targeted database platform.
  377. *
  378. * @param Doctrine\ORM\Mapping\ClassMetadata $class
  379. */
  380. private function completeIdGeneratorMapping(ClassMetadataInfo $class)
  381. {
  382. $idGenType = $class->generatorType;
  383. if ($idGenType == ClassMetadata::GENERATOR_TYPE_AUTO) {
  384. if ($this->targetPlatform->prefersSequences()) {
  385. $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_SEQUENCE);
  386. } else if ($this->targetPlatform->prefersIdentityColumns()) {
  387. $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
  388. } else {
  389. $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_TABLE);
  390. }
  391. }
  392. // Create & assign an appropriate ID generator instance
  393. switch ($class->generatorType) {
  394. case ClassMetadata::GENERATOR_TYPE_IDENTITY:
  395. // For PostgreSQL IDENTITY (SERIAL) we need a sequence name. It defaults to
  396. // <table>_<column>_seq in PostgreSQL for SERIAL columns.
  397. // Not pretty but necessary and the simplest solution that currently works.
  398. $seqName = $this->targetPlatform instanceof Platforms\PostgreSQLPlatform ?
  399. $class->table['name'] . '_' . $class->columnNames[$class->identifier[0]] . '_seq' :
  400. null;
  401. $class->setIdGenerator(new \Doctrine\ORM\Id\IdentityGenerator($seqName));
  402. break;
  403. case ClassMetadata::GENERATOR_TYPE_SEQUENCE:
  404. // If there is no sequence definition yet, create a default definition
  405. $definition = $class->sequenceGeneratorDefinition;
  406. if ( ! $definition) {
  407. $sequenceName = $class->getTableName() . '_' . $class->getSingleIdentifierColumnName() . '_seq';
  408. $definition['sequenceName'] = $this->targetPlatform->fixSchemaElementName($sequenceName);
  409. $definition['allocationSize'] = 1;
  410. $definition['initialValue'] = 1;
  411. $class->setSequenceGeneratorDefinition($definition);
  412. }
  413. $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator(
  414. $definition['sequenceName'],
  415. $definition['allocationSize']
  416. );
  417. $class->setIdGenerator($sequenceGenerator);
  418. break;
  419. case ClassMetadata::GENERATOR_TYPE_NONE:
  420. $class->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
  421. break;
  422. case ClassMetadata::GENERATOR_TYPE_TABLE:
  423. throw new ORMException("TableGenerator not yet implemented.");
  424. break;
  425. default:
  426. throw new ORMException("Unknown generator type: " . $class->generatorType);
  427. }
  428. }
  429. }