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.
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>.
20 namespace Doctrine\ORM\Mapping;
22 use ReflectionException,
23 Doctrine\ORM\ORMException,
24 Doctrine\ORM\EntityManager,
25 Doctrine\DBAL\Platforms,
27 Doctrine\Common\Persistence\Mapping\ReflectionService,
28 Doctrine\Common\Persistence\Mapping\ClassMetadata as ClassMetadataInterface,
29 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory,
30 Doctrine\ORM\Id\IdentityGenerator,
31 Doctrine\ORM\Event\LoadClassMetadataEventArgs;
34 * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
35 * metadata mapping information of a class which describes how a class should be mapped
36 * to a relational database.
39 * @author Benjamin Eberlei <kontakt@beberlei.de>
40 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
41 * @author Jonathan Wage <jonwage@gmail.com>
42 * @author Roman Borschel <roman@code-factory.org>
44 class ClassMetadataFactory extends AbstractClassMetadataFactory
52 * @var \Doctrine\DBAL\Platforms\AbstractPlatform
54 private $targetPlatform;
57 * @var \Doctrine\Common\Persistence\Mapping\Driver\MappingDriver
62 * @var \Doctrine\Common\EventManager
67 * @param EntityManager $em
69 public function setEntityManager(EntityManager $em)
77 protected function initialize()
79 $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl();
80 $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform();
81 $this->evm = $this->em->getEventManager();
82 $this->initialized = true;
88 protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents)
90 /* @var $class ClassMetadata */
91 /* @var $parent ClassMetadata */
93 $class->setInheritanceType($parent->inheritanceType);
94 $class->setDiscriminatorColumn($parent->discriminatorColumn);
95 $class->setIdGeneratorType($parent->generatorType);
96 $this->addInheritedFields($class, $parent);
97 $this->addInheritedRelations($class, $parent);
98 $class->setIdentifier($parent->identifier);
99 $class->setVersioned($parent->isVersioned);
100 $class->setVersionField($parent->versionField);
101 $class->setDiscriminatorMap($parent->discriminatorMap);
102 $class->setLifecycleCallbacks($parent->lifecycleCallbacks);
103 $class->setChangeTrackingPolicy($parent->changeTrackingPolicy);
105 if ($parent->isMappedSuperclass) {
106 $class->setCustomRepositoryClass($parent->customRepositoryClassName);
112 $this->driver->loadMetadataForClass($class->getName(), $class);
113 } catch (ReflectionException $e) {
114 throw MappingException::reflectionFailure($class->getName(), $e);
117 // If this class has a parent the id generator strategy is inherited.
118 // However this is only true if the hierarchy of parents contains the root entity,
119 // if it consists of mapped superclasses these don't necessarily include the id field.
120 if ($parent && $rootEntityFound) {
121 if ($parent->isIdGeneratorSequence()) {
122 $class->setSequenceGeneratorDefinition($parent->sequenceGeneratorDefinition);
123 } else if ($parent->isIdGeneratorTable()) {
124 $class->tableGeneratorDefinition = $parent->tableGeneratorDefinition;
127 if ($parent->generatorType) {
128 $class->setIdGeneratorType($parent->generatorType);
131 if ($parent->idGenerator) {
132 $class->setIdGenerator($parent->idGenerator);
135 $this->completeIdGeneratorMapping($class);
138 if ($parent && $parent->isInheritanceTypeSingleTable()) {
139 $class->setPrimaryTable($parent->table);
142 if ($parent && $parent->containsForeignIdentifier) {
143 $class->containsForeignIdentifier = true;
146 if ($parent && !empty($parent->namedQueries)) {
147 $this->addInheritedNamedQueries($class, $parent);
150 if ($parent && !empty($parent->namedNativeQueries)) {
151 $this->addInheritedNamedNativeQueries($class, $parent);
154 if ($parent && !empty($parent->sqlResultSetMappings)) {
155 $this->addInheritedSqlResultSetMappings($class, $parent);
158 $class->setParentClasses($nonSuperclassParents);
160 if ( $class->isRootEntity() && ! $class->isInheritanceTypeNone() && ! $class->discriminatorMap) {
161 $this->addDefaultDiscriminatorMap($class);
164 if ($this->evm->hasListeners(Events::loadClassMetadata)) {
165 $eventArgs = new LoadClassMetadataEventArgs($class, $this->em);
166 $this->evm->dispatchEvent(Events::loadClassMetadata, $eventArgs);
169 $this->wakeupReflection($class, $this->getReflectionService());
170 $this->validateRuntimeMetadata($class, $parent);
174 * Validate runtime metadata is correctly defined.
176 * @param ClassMetadata $class
178 * @throws MappingException
180 protected function validateRuntimeMetadata($class, $parent)
182 if ( ! $class->reflClass ) {
183 // only validate if there is a reflection class instance
187 $class->validateIdentifier();
188 $class->validateAssocations();
189 $class->validateLifecycleCallbacks($this->getReflectionService());
191 // verify inheritance
192 if ( ! $class->isMappedSuperclass && !$class->isInheritanceTypeNone()) {
194 if (count($class->discriminatorMap) == 0) {
195 throw MappingException::missingDiscriminatorMap($class->name);
197 if ( ! $class->discriminatorColumn) {
198 throw MappingException::missingDiscriminatorColumn($class->name);
200 } else if ($parent && !$class->reflClass->isAbstract() && !in_array($class->name, array_values($class->discriminatorMap))) {
201 // enforce discriminator map for all entities of an inheritance hierarchy, otherwise problems will occur.
202 throw MappingException::mappedClassNotPartOfDiscriminatorMap($class->name, $class->rootEntityName);
204 } else if ($class->isMappedSuperclass && $class->name == $class->rootEntityName && (count($class->discriminatorMap) || $class->discriminatorColumn)) {
205 // second condition is necessary for mapped superclasses in the middle of an inheritance hierarchy
206 throw MappingException::noInheritanceOnMappedSuperClass($class->name);
213 protected function newClassMetadataInstance($className)
215 return new ClassMetadata($className, $this->em->getConfiguration()->getNamingStrategy());
219 * Adds a default discriminator map if no one is given
221 * If an entity is of any inheritance type and does not contain a
222 * discriminator map, then the map is generated automatically. This process
223 * is expensive computation wise.
225 * The automatically generated discriminator map contains the lowercase short name of
228 * @param \Doctrine\ORM\Mapping\ClassMetadata $class
229 * @throws MappingException
231 private function addDefaultDiscriminatorMap(ClassMetadata $class)
233 $allClasses = $this->driver->getAllClassNames();
234 $fqcn = $class->getName();
235 $map = array($this->getShortName($class->name) => $fqcn);
237 $duplicates = array();
238 foreach ($allClasses as $subClassCandidate) {
239 if (is_subclass_of($subClassCandidate, $fqcn)) {
240 $shortName = $this->getShortName($subClassCandidate);
242 if (isset($map[$shortName])) {
243 $duplicates[] = $shortName;
246 $map[$shortName] = $subClassCandidate;
251 throw MappingException::duplicateDiscriminatorEntry($class->name, $duplicates, $map);
254 $class->setDiscriminatorMap($map);
258 * Get the lower-case short name of a class.
260 * @param string $className
263 private function getShortName($className)
265 if (strpos($className, "\\") === false) {
266 return strtolower($className);
269 $parts = explode("\\", $className);
270 return strtolower(end($parts));
274 * Adds inherited fields to the subclass mapping.
276 * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
277 * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
279 private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $parentClass)
281 foreach ($parentClass->fieldMappings as $mapping) {
282 if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
283 $mapping['inherited'] = $parentClass->name;
285 if ( ! isset($mapping['declared'])) {
286 $mapping['declared'] = $parentClass->name;
288 $subClass->addInheritedFieldMapping($mapping);
290 foreach ($parentClass->reflFields as $name => $field) {
291 $subClass->reflFields[$name] = $field;
296 * Adds inherited association mappings to the subclass mapping.
298 * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
299 * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
300 * @throws MappingException
302 private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $parentClass)
304 foreach ($parentClass->associationMappings as $field => $mapping) {
305 if ($parentClass->isMappedSuperclass) {
306 if ($mapping['type'] & ClassMetadata::TO_MANY && !$mapping['isOwningSide']) {
307 throw MappingException::illegalToManyAssocationOnMappedSuperclass($parentClass->name, $field);
309 $mapping['sourceEntity'] = $subClass->name;
312 //$subclassMapping = $mapping;
313 if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
314 $mapping['inherited'] = $parentClass->name;
316 if ( ! isset($mapping['declared'])) {
317 $mapping['declared'] = $parentClass->name;
319 $subClass->addInheritedAssociationMapping($mapping);
324 * Adds inherited named queries to the subclass mapping.
327 * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
328 * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
330 private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata $parentClass)
332 foreach ($parentClass->namedQueries as $name => $query) {
333 if ( ! isset ($subClass->namedQueries[$name])) {
334 $subClass->addNamedQuery(array(
335 'name' => $query['name'],
336 'query' => $query['query']
343 * Adds inherited named native queries to the subclass mapping.
346 * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
347 * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
349 private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMetadata $parentClass)
351 foreach ($parentClass->namedNativeQueries as $name => $query) {
352 if ( ! isset ($subClass->namedNativeQueries[$name])) {
353 $subClass->addNamedNativeQuery(array(
354 'name' => $query['name'],
355 'query' => $query['query'],
356 'isSelfClass' => $query['isSelfClass'],
357 'resultSetMapping' => $query['resultSetMapping'],
358 'resultClass' => $query['isSelfClass'] ? $subClass->name : $query['resultClass'],
365 * Adds inherited sql result set mappings to the subclass mapping.
368 * @param \Doctrine\ORM\Mapping\ClassMetadata $subClass
369 * @param \Doctrine\ORM\Mapping\ClassMetadata $parentClass
371 private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, ClassMetadata $parentClass)
373 foreach ($parentClass->sqlResultSetMappings as $name => $mapping) {
374 if ( ! isset ($subClass->sqlResultSetMappings[$name])) {
376 foreach ($mapping['entities'] as $entity) {
378 'fields' => $entity['fields'],
379 'isSelfClass' => $entity['isSelfClass'],
380 'discriminatorColumn' => $entity['discriminatorColumn'],
381 'entityClass' => $entity['isSelfClass'] ? $subClass->name : $entity['entityClass'],
385 $subClass->addSqlResultSetMapping(array(
386 'name' => $mapping['name'],
387 'columns' => $mapping['columns'],
388 'entities' => $entities,
395 * Completes the ID generator mapping. If "auto" is specified we choose the generator
396 * most appropriate for the targeted database platform.
398 * @param ClassMetadataInfo $class
399 * @throws ORMException
401 private function completeIdGeneratorMapping(ClassMetadataInfo $class)
403 $idGenType = $class->generatorType;
404 if ($idGenType == ClassMetadata::GENERATOR_TYPE_AUTO) {
405 if ($this->targetPlatform->prefersSequences()) {
406 $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_SEQUENCE);
407 } else if ($this->targetPlatform->prefersIdentityColumns()) {
408 $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
410 $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_TABLE);
414 // Create & assign an appropriate ID generator instance
415 switch ($class->generatorType) {
416 case ClassMetadata::GENERATOR_TYPE_IDENTITY:
417 // For PostgreSQL IDENTITY (SERIAL) we need a sequence name. It defaults to
418 // <table>_<column>_seq in PostgreSQL for SERIAL columns.
419 // Not pretty but necessary and the simplest solution that currently works.
420 $sequenceName = null;
422 if ($this->targetPlatform instanceof Platforms\PostgreSQLPlatform) {
423 $fieldName = $class->getSingleIdentifierFieldName();
424 $columnName = $class->getSingleIdentifierColumnName();
425 $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']);
426 $sequenceName = $class->getTableName() . '_' . $columnName . '_seq';
428 'sequenceName' => $this->targetPlatform->fixSchemaElementName($sequenceName)
432 $definition['quoted'] = true;
435 $sequenceName = $this->em->getConfiguration()->getQuoteStrategy()->getSequenceName($definition, $class, $this->targetPlatform);
438 $class->setIdGenerator(new \Doctrine\ORM\Id\IdentityGenerator($sequenceName));
441 case ClassMetadata::GENERATOR_TYPE_SEQUENCE:
442 // If there is no sequence definition yet, create a default definition
443 $definition = $class->sequenceGeneratorDefinition;
445 if ( ! $definition) {
446 $fieldName = $class->getSingleIdentifierFieldName();
447 $columnName = $class->getSingleIdentifierColumnName();
448 $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']);
449 $sequenceName = $class->getTableName() . '_' . $columnName . '_seq';
451 'sequenceName' => $this->targetPlatform->fixSchemaElementName($sequenceName),
452 'allocationSize' => 1,
457 $definition['quoted'] = true;
460 $class->setSequenceGeneratorDefinition($definition);
463 $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator(
464 $this->em->getConfiguration()->getQuoteStrategy()->getSequenceName($definition, $class, $this->targetPlatform),
465 $definition['allocationSize']
467 $class->setIdGenerator($sequenceGenerator);
470 case ClassMetadata::GENERATOR_TYPE_NONE:
471 $class->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
474 case ClassMetadata::GENERATOR_TYPE_UUID:
475 $class->setIdGenerator(new \Doctrine\ORM\Id\UuidGenerator());
478 case ClassMetadata::GENERATOR_TYPE_TABLE:
479 throw new ORMException("TableGenerator not yet implemented.");
482 case ClassMetadata::GENERATOR_TYPE_CUSTOM:
483 $definition = $class->customGeneratorDefinition;
484 if ( ! class_exists($definition['class'])) {
485 throw new ORMException("Can't instantiate custom generator : " .
486 $definition['class']);
488 $class->setIdGenerator(new $definition['class']);
492 throw new ORMException("Unknown generator type: " . $class->generatorType);
499 protected function wakeupReflection(ClassMetadataInterface $class, ReflectionService $reflService)
501 /* @var $class ClassMetadata */
502 $class->wakeupReflection($reflService);
508 protected function initializeReflection(ClassMetadataInterface $class, ReflectionService $reflService)
510 /* @var $class ClassMetadata */
511 $class->initializeReflection($reflService);
517 protected function getFqcnFromAlias($namespaceAlias, $simpleClassName)
519 return $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName;
525 protected function getDriver()
527 return $this->driver;
533 protected function isEntity(ClassMetadataInterface $class)
535 return isset($class->isMappedSuperclass) && $class->isMappedSuperclass === false;