private function mapStringUser(ClassMetadata $classMetadata) { if (!$classMetadata->hasField('createdBy')) { $classMetadata->mapField(['fieldName' => 'createdBy', 'type' => 'string', 'nullable' => true]); } if (!$classMetadata->hasField('updatedBy')) { $classMetadata->mapField(['fieldName' => 'updatedBy', 'type' => 'string', 'nullable' => true]); } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata * * @throws \Exception * @return void */ public function loadMetadataForClass($className, ClassMetadata $metadata) { if (!$metadata instanceof \Doctrine\ORM\Mapping\ClassMetadata) { throw new \Exception('Error: class metadata object is the wrong type'); } $refClass = new \ReflectionClass($className); $classDocBlock = $refClass->getDocComment(); if (!$classDocBlock || strpos($classDocBlock, '@Table') === false) { $metadata->setPrimaryTable(['name' => $this->_getTableName($className)]); } $needAutoGenerator = false; foreach ($refClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop) { $propName = $prop->getName(); try { $mapping = $metadata->getFieldMapping($propName); } catch (MappingException $e) { $mapping = null; } if (!$mapping) { if ($propName == 'createdAt') { if (!$this->isTransient($className) && !$refClass->isAbstract() && call_user_func($className . '::useAutoTimestamp')) { $metadata->mapField(['fieldName' => 'createdAt', 'columnName' => call_user_func($className . '::getCreatedAtColumn'), 'type' => 'datetime']); } } else { if ($propName == 'updatedAt') { if (!$this->isTransient($className) && !$refClass->isAbstract() && call_user_func($className . '::useAutoTimestamp')) { $metadata->mapField(['fieldName' => 'updatedAt', 'columnName' => call_user_func($className . '::getUpdatedAtColumn'), 'type' => 'datetime']); } } else { $columnName = Inflector::tableize($propName); $fieldMap = ['fieldName' => $propName, 'columnName' => $columnName, 'type' => $this->_getDefaultDataType($columnName)]; if ($columnName == 'id') { $fieldMap['id'] = true; $fieldMap['autoincrement'] = true; $fieldMap['unsigned'] = true; $needAutoGenerator = true; } else { if (in_array($columnName, ['price', 'tax', 'amount', 'cost', 'total'])) { // DECIMAL(10,2) $fieldMap['precision'] = 10; $fieldMap['scale'] = 2; } } $metadata->mapField($fieldMap); } } } } if ($needAutoGenerator && !$metadata->usesIdGenerator()) { $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_AUTO); } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $class = $metadata->getReflectionClass(); if (!$class) { // this happens when running annotation driver in combination with // static reflection services. This is not the nicest fix $class = new \ReflectionClass($metadata->name); } $entityAnnot = $this->reader->getClassAnnotation($class, 'Doctrine\\KeyValueStore\\Mapping\\Annotations\\Entity'); if (!$entityAnnot) { throw new \InvalidArgumentException($metadata->name . ' is not a valid key-value-store entity.'); } $metadata->storageName = $entityAnnot->storageName; // Evaluate annotations on properties/fields foreach ($class->getProperties() as $property) { $idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\KeyValueStore\\Mapping\\Annotations\\Id'); $transientAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\KeyValueStore\\Mapping\\Annotations\\Transient'); if ($idAnnot) { $metadata->mapIdentifier($property->getName()); } elseif ($transientAnnot) { $metadata->skipTransientField($property->getName()); } else { $metadata->mapField(['fieldName' => $property->getName()]); } } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { /** @var $class ClassMetadataInfo */ $reflClass = $metadata->getReflectionClass(); if ($entityAnnot = $this->reader->getClassAnnotation($reflClass, 'Pasinter\\OHM\\Mapping\\Annotations\\Entity')) { $metadata->database = $entityAnnot->database; } // Evaluate annotations on properties/fields foreach ($reflClass->getProperties() as $property) { if ($fieldAnnot = $this->reader->getPropertyAnnotation($property, 'Pasinter\\OHM\\Mapping\\Annotations\\Field')) { $mapping = $this->fieldToArray($property->getName(), $fieldAnnot); if ($this->reader->getPropertyAnnotation($property, 'Pasinter\\OHM\\Mapping\\Annotations\\Id')) { $mapping['id'] = true; } $metadata->mapField($mapping); } elseif ($referenceOneAnnot = $this->reader->getPropertyAnnotation($property, 'Pasinter\\OHM\\Mapping\\Annotations\\ReferenceOne')) { $mapping = $this->referenceOneToArray($property->getName(), $referenceOneAnnot); $metadata->mapOneReference($mapping); } elseif ($referenceManyAnnot = $this->reader->getPropertyAnnotation($property, 'Pasinter\\OHM\\Mapping\\Annotations\\ReferenceMany')) { $mapping = $this->referenceManyToArray($property->getName(), $referenceManyAnnot); $metadata->mapManyReference($mapping); } elseif ($embedOneAnnot = $this->reader->getPropertyAnnotation($property, 'Pasinter\\OHM\\Mapping\\Annotations\\EmbedOne')) { $mapping = $this->embedOneToArray($property->getName(), $embedOneAnnot); $metadata->mapOneEmbed($mapping); } elseif ($embedManyAnnot = $this->reader->getPropertyAnnotation($property, 'Pasinter\\OHM\\Mapping\\Annotations\\EmbedMany')) { $mapping = $this->embedManyToArray($property->getName(), $embedManyAnnot); $metadata->mapManyEmbed($mapping); } } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param CommonClassMetadata $metadata * * @return void */ public function loadMetadataForClass($className, CommonClassMetadata $metadata) { /** @var \Doctrine\KeyValueStore\Mapping\ClassMetadata $metadata */ try { $element = $this->getElement($className); } catch (MappingException $exception) { throw new \InvalidArgumentException($metadata->name . ' is not a valid key-value-store entity.'); } $class = new \ReflectionClass($className); if (isset($element['storageName'])) { $metadata->storageName = $element['storageName']; } $ids = []; if (isset($element['id'])) { $ids = $element['id']; } $transients = []; if (isset($element['transient'])) { $transients = $element['transient']; } foreach ($class->getProperties() as $property) { if (in_array($property->getName(), $ids)) { $metadata->mapIdentifier($property->getName()); continue; } if (in_array($property->getName(), $transients)) { $metadata->skipTransientField($property->getName()); continue; } $metadata->mapField(array('fieldName' => $property->getName())); } }
protected function initializeReflection(ClassMetadata $class, ReflectionService $reflService) { $class->reflClass = $reflService->getClass($class->name); if ($class->reflClass) { foreach ($class->reflClass->getProperties() as $property) { $class->mapField(['fieldName' => $property->getName()]); } } }
public function loadMetadataForClass($className, ClassMetadata $metadata) { if ($className === 'Mapping\\Fixture\\Unmapped\\Timestampable') { $id = array(); $id['fieldName'] = 'id'; $id['type'] = 'integer'; $id['nullable'] = false; $id['columnName'] = 'id'; $id['id'] = true; $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_AUTO')); $metadata->mapField($id); $created = array(); $created['fieldName'] = 'created'; $created['type'] = 'datetime'; $created['nullable'] = false; $created['columnName'] = 'created'; $metadata->mapField($created); } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata * * @return void */ public function loadMetadataForClass($className, ClassMetadata $metadata) { if (!$this->isTransient($className)) { throw new MappingException('Class ' . $className . 'has no appropriate ModelConfiguration'); } $modelConfig = $className::getConfiguration(); $table = $modelConfig->getTable(); $table['name'] = SQL_TABLE_PREFIX . $table['name']; $metadata->setPrimaryTable($table); foreach ($modelConfig->getFields() as $fieldName => $config) { self::mapTypes($config); if (!$config['doctrineIgnore']) { $metadata->mapField($config); } } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata * * @return void */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $originClassName = $className; $originMetadata = $this->em->getClassMetadata('Opifer\\ContentBundle\\Entity\\ListBlock'); // // $metadata->name = self::REVISION_ENTITY; //. '' . str_replace('\\', '', $class->name); // $class->rootEntityName = $class->name; // $class->namespace = 'Opifer\\Revisions\\Entity'; // // $class->discriminatorMap = null; // $class->discriminatorColumn = null; $metadata->setPrimaryTable(['name' => $originMetadata->getTableName() . '_revisions']); foreach ($originMetadata->fieldMappings as $key => $fieldMapping) { $fieldMapping['inherited'] = self::REVISION_ENTITY; $fieldMapping['declared'] = self::REVISION_ENTITY; if ($this->annotationReader->isPropertyRevised($originClassName, $fieldMapping['fieldName'])) { $metadata->mapField($fieldMapping); } } foreach ($originMetadata->associationMappings as $key => $associationMapping) { $associationMapping['inherited'] = self::REVISION_ENTITY; $associationMapping['declared'] = self::REVISION_ENTITY; if ($this->annotationReader->isPropertyRevised($originClassName, $associationMapping['fieldName'])) { if ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_ONE) { $metadata->mapOneToOne($associationMapping); } else { if ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_ONE) { $metadata->mapManyToOne($associationMapping); } else { if ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { $metadata->mapOneToMany($associationMapping); } else { if ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { $metadata->mapManyToMany($associationMapping); } } } } } } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param EntityMetadata|ClassMetadata $metadata * * @return void * @throws MappingException */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $element = $this->getElement($className); switch ($element['type']) { case 'entity': if (array_key_exists('repositoryClass', $element)) { $metadata->setCustomRepositoryClass($element['repositoryClass']); } break; case 'mappedSuperclass': $metadata->isMappedSuperclass = true; $metadata->setCustomRepositoryClass(array_key_exists('repositoryClass', $element) ? $element['repositoryClass'] : null); break; } if (null === $metadata->searcher) { $metadata->searcher = DoctrineApi::class; } if (null === $metadata->finder) { $metadata->finder = DoctrineApi::class; } // Configure client if (array_key_exists('client', $element)) { if (array_key_exists('name', $element['client'])) { $metadata->clientName = $element['client']['name']; } if (array_key_exists('searcher', $element['client'])) { $metadata->searcher = $element['client']['searcher']; } if (array_key_exists('finder', $element['client'])) { $metadata->finder = $element['client']['finder']; } assert(in_array(Searcher::class, class_implements($metadata->searcher), true), 'Searcher ' . $metadata->searcher . ' should implement ' . Searcher::class); assert(in_array(Finder::class, class_implements($metadata->finder), true), 'Finder ' . $metadata->finder . ' should implement ' . Finder::class); $methodProvider = null; if (array_key_exists('methods', $element['client'])) { $methodProvider = new MethodProvider($element['client']['methods']); } if (array_key_exists('entityPath', $element['client'])) { $pathSeparator = array_key_exists('entityPathSeparator', $element['client']) ? $element['client']['entityPathSeparator'] : null; $methodProvider = new EntityMethodProvider($element['client']['entityPath'], $pathSeparator, $methodProvider); } if (null === $methodProvider) { throw MappingException::noMethods(); } $metadata->methodProvider = $methodProvider; } // Configure fields if (array_key_exists('fields', $element)) { foreach ($element['fields'] as $field => $mapping) { $mapping = $this->fieldToArray($field, $mapping); $metadata->mapField($mapping); } } // Configure identifiers $associationIds = []; if (array_key_exists('id', $element)) { // Evaluate identifier settings foreach ($element['id'] as $name => $idElement) { if (isset($idElement['associationKey']) && (bool) $idElement['associationKey'] === true) { $associationIds[$name] = true; continue; } $mapping = $this->fieldToArray($name, $idElement); $mapping['id'] = true; $metadata->mapField($mapping); } } foreach (['oneToOne', 'manyToOne', 'oneToMany'] as $type) { if (array_key_exists($type, $element)) { $associations = $element[$type]; foreach ($associations as $name => $association) { $this->mapAssociation($metadata, $type, $name, $association, $associationIds); } } } }
private function addMappingFromReference(ClassMetadata $class, $fieldName, $reference, $type) { $class->mapField(array('type' => $type, 'reference' => true, 'targetDocument' => isset($reference['targetDocument']) ? $reference['targetDocument'] : null, 'fieldName' => $fieldName, 'strategy' => isset($reference['strategy']) ? (string) $reference['strategy'] : 'pushPull')); }
/** * Add a "deletedAt" field to a SoftDeletable entity, if necessary * * @param ClassMetadata $classMetadata */ protected function mapDeletedAt(ClassMetadata $classMetadata) { if (!$classMetadata->hasField(self::DELETED_AT_FIELD)) { $classMetadata->mapField(['fieldName' => self::DELETED_AT_FIELD, 'type' => 'datetime', 'nullable' => true]); } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { /** @var $metadata \Doctrine\ODM\PHPCR\Mapping\ClassMetadata */ $reflClass = $metadata->getReflectionClass(); $documentAnnots = array(); foreach ($this->reader->getClassAnnotations($reflClass) as $annot) { foreach ($this->entityAnnotationClasses as $annotClass => $i) { if ($annot instanceof $annotClass) { $documentAnnots[$i] = $annot; } } } if (!$documentAnnots) { throw MappingException::classIsNotAValidDocument($className); } // find the winning document annotation ksort($documentAnnots); $documentAnnot = reset($documentAnnots); if ($documentAnnot instanceof ODM\MappedSuperclass) { $metadata->isMappedSuperclass = true; } if (null !== $documentAnnot->referenceable) { $metadata->setReferenceable($documentAnnot->referenceable); } if (null !== $documentAnnot->versionable) { $metadata->setVersioned($documentAnnot->versionable); } if (null !== $documentAnnot->mixins) { $metadata->setMixins($documentAnnot->mixins); } if (null !== $documentAnnot->inheritMixins) { $metadata->setInheritMixins($documentAnnot->inheritMixins); } if (null !== $documentAnnot->nodeType) { $metadata->setNodeType($documentAnnot->nodeType); } if (null !== $documentAnnot->repositoryClass) { $metadata->setCustomRepositoryClassName($documentAnnot->repositoryClass); } if (null !== $documentAnnot->translator) { $metadata->setTranslator($documentAnnot->translator); } foreach ($reflClass->getProperties() as $property) { if ($metadata->isInheritedField($property->name) && $metadata->name !== $property->getDeclaringClass()->getName()) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) { if ($fieldAnnot instanceof ODM\Property) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapField($mapping); } elseif ($fieldAnnot instanceof ODM\Id) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapId($mapping); } elseif ($fieldAnnot instanceof ODM\Node) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapNode($mapping); } elseif ($fieldAnnot instanceof ODM\Nodename) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapNodename($mapping); } elseif ($fieldAnnot instanceof ODM\ParentDocument) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); $metadata->mapParentDocument($mapping); } elseif ($fieldAnnot instanceof ODM\Child) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); $metadata->mapChild($mapping); } elseif ($fieldAnnot instanceof ODM\Children) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); $metadata->mapChildren($mapping); } elseif ($fieldAnnot instanceof ODM\ReferenceOne) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); $metadata->mapManyToOne($mapping); } elseif ($fieldAnnot instanceof ODM\ReferenceMany) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); $metadata->mapManyToMany($mapping); } elseif ($fieldAnnot instanceof ODM\Referrers) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); $metadata->mapReferrers($mapping); } elseif ($fieldAnnot instanceof ODM\MixedReferrers) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapMixedReferrers($mapping); } elseif ($fieldAnnot instanceof ODM\Locale) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapLocale($mapping); } elseif ($fieldAnnot instanceof ODM\Depth) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapDepth($mapping); } elseif ($fieldAnnot instanceof ODM\VersionName) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapVersionName($mapping); } elseif ($fieldAnnot instanceof ODM\VersionCreated) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapVersionCreated($mapping); } } } foreach ($reflClass->getMethods() as $method) { if ($method->isPublic() && $method->getDeclaringClass()->getName() == $metadata->name) { foreach ($this->reader->getMethodAnnotations($method) as $annot) { if ($annot instanceof ODM\PrePersist) { $metadata->addLifecycleCallback($method->getName(), Event::prePersist); } elseif ($annot instanceof ODM\PostPersist) { $metadata->addLifecycleCallback($method->getName(), Event::postPersist); } elseif ($annot instanceof ODM\PreUpdate) { $metadata->addLifecycleCallback($method->getName(), Event::preUpdate); } elseif ($annot instanceof ODM\PostUpdate) { $metadata->addLifecycleCallback($method->getName(), Event::postUpdate); } elseif ($annot instanceof ODM\PreRemove) { $metadata->addLifecycleCallback($method->getName(), Event::preRemove); } elseif ($annot instanceof ODM\PostRemove) { $metadata->addLifecycleCallback($method->getName(), Event::postRemove); } elseif ($annot instanceof ODM\PostLoad) { $metadata->addLifecycleCallback($method->getName(), Event::postLoad); } } } } $metadata->validateClassMapping(); }
/** * Adds mapping to single field * * @param string $field */ protected function mapField($field) { if (!$this->classMetadata->hasField($field)) { $this->classMetadata->mapField(['fieldName' => $field, 'type' => 'datetime', 'nullable' => true]); } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param CommonClassMetadata $metadata * * @return void */ public function loadMetadataForClass($className, CommonClassMetadata $metadata) { try { $xmlRoot = $this->getElement($className); } catch (MappingException $exception) { throw new \InvalidArgumentException($metadata->name . ' is not a valid key-value-store entity.'); } if ($xmlRoot->getName() != 'entity') { throw new \InvalidArgumentException($metadata->name . ' is not a valid key-value-store entity.'); } $class = new \ReflectionClass($className); if (isset($xmlRoot['storage-name'])) { $metadata->storageName = $xmlRoot['storage-name']; } $ids = []; if (isset($xmlRoot->id)) { foreach ($xmlRoot->id as $id) { $ids[] = (string) $id; } } $transients = []; if (isset($xmlRoot->transient)) { foreach ($xmlRoot->transient as $transient) { $transients[] = (string) $transient; } } foreach ($class->getProperties() as $property) { if (in_array($property->getName(), $ids)) { $metadata->mapIdentifier($property->getName()); continue; } if (in_array($property->getName(), $transients)) { $metadata->skipTransientField($property->getName()); continue; } $metadata->mapField(array('fieldName' => $property->getName())); } }
/** * Add a "metaKeywords" field * * @param ClassMetadata $classMetadata */ protected function mapMetaKeywords(ClassMetadata $classMetadata) { if (!$classMetadata->hasField(self::META_KEYWORDS)) { $classMetadata->mapField(['fieldName' => self::META_KEYWORDS, 'type' => 'string', 'length' => 255, 'nullable' => true]); } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $class) { /** @var $class \Doctrine\ODM\PHPCR\Mapping\ClassMetadata */ try { $xmlRoot = $this->getElement($className); } catch (DoctrineMappingException $e) { // Convert Exception type for consistency with other drivers throw new MappingException($e->getMessage(), $e->getCode(), $e); } if (!$xmlRoot) { return; } if (isset($xmlRoot['repository-class'])) { $class->setCustomRepositoryClassName((string) $xmlRoot['repository-class']); } if (isset($xmlRoot['translator'])) { $class->setTranslator((string) $xmlRoot['translator']); } if (isset($xmlRoot['versionable']) && $xmlRoot['versionable'] !== 'false') { $class->setVersioned(strtolower($xmlRoot['versionable'])); } if (isset($xmlRoot['referenceable']) && $xmlRoot['referenceable'] !== 'false') { $class->setReferenceable((bool) $xmlRoot['referenceable']); } if (isset($xmlRoot->mixins)) { $mixins = array(); foreach ($xmlRoot->mixins->mixin as $mixin) { $attributes = $mixin->attributes(); if (!isset($attributes['type'])) { throw new MappingException('<mixin> missing mandatory type attribute'); } $mixins[] = (string) $attributes['type']; } $class->setMixins($mixins); } if (isset($xmlRoot['node-type'])) { $class->setNodeType((string) $xmlRoot['node-type']); } if ($xmlRoot->getName() === 'mapped-superclass') { $class->isMappedSuperclass = true; } if (isset($xmlRoot->field)) { foreach ($xmlRoot->field as $field) { $mapping = array(); $attributes = $field->attributes(); foreach ($attributes as $key => $value) { $mapping[$key] = (string) $value; // convert bool fields if (in_array($key, array('id', 'multivalue', 'assoc', 'translated', 'nullable'))) { $mapping[$key] = 'true' === $mapping[$key] ? true : false; } } if (!isset($mapping['name'])) { throw new MappingException(sprintf('Missing name attribute for field of %s', $className)); } $mapping['fieldName'] = $mapping['name']; unset($mapping['name']); $class->mapField($mapping); } } if (isset($xmlRoot->id)) { $mapping = array('fieldName' => (string) $xmlRoot->id->attributes()->name, 'id' => true); if (isset($xmlRoot->id->generator) && isset($xmlRoot->id->generator->attributes()->strategy)) { $mapping['strategy'] = (string) $xmlRoot->id->generator->attributes()->strategy; } $class->mapId($mapping); } if (isset($xmlRoot->node)) { $class->mapNode(array('fieldName' => (string) $xmlRoot->node->attributes()->name)); } if (isset($xmlRoot->nodename)) { $class->mapNodename(array('fieldName' => (string) $xmlRoot->nodename->attributes()->name)); } if (isset($xmlRoot->{'parent-document'})) { $mapping = array('fieldName' => (string) $xmlRoot->{'parent-document'}->attributes()->name, 'cascade' => isset($xmlRoot->{'parent-document'}->cascade) ? $this->getCascadeMode($xmlRoot->{'parent-document'}->cascade) : 0); $class->mapParentDocument($mapping); } if (isset($xmlRoot->child)) { foreach ($xmlRoot->child as $child) { $attributes = $child->attributes(); $mapping = array('fieldName' => (string) $attributes->name, 'cascade' => isset($child->cascade) ? $this->getCascadeMode($child->cascade) : 0); if (isset($attributes['node-name'])) { $mapping['nodeName'] = (string) $attributes->{'node-name'}; } $class->mapChild($mapping); } } if (isset($xmlRoot->children)) { foreach ($xmlRoot->children as $children) { $attributes = $children->attributes(); $mapping = array('fieldName' => (string) $attributes->name, 'cascade' => isset($children->cascade) ? $this->getCascadeMode($children->cascade) : 0, 'filter' => isset($attributes['filter']) ? (array) $attributes->filter : null, 'fetchDepth' => isset($attributes['fetch-depth']) ? (int) $attributes->{'fetch-depth'} : -1, 'ignoreUntranslated' => !empty($attributes['ignore-untranslated'])); $class->mapChildren($mapping); } } if (isset($xmlRoot->{'reference-many'})) { foreach ($xmlRoot->{'reference-many'} as $reference) { $attributes = $reference->attributes(); $reference['cascade'] = isset($reference->cascade) ? $this->getCascadeMode($reference->cascade) : 0; $reference['fieldName'] = (string) $attributes->name ?: null; $this->addReferenceMapping($class, $reference, 'many'); } } if (isset($xmlRoot->{'reference-one'})) { foreach ($xmlRoot->{'reference-one'} as $reference) { $attributes = $reference->attributes(); $reference['cascade'] = isset($reference->cascade) ? $this->getCascadeMode($reference->cascade) : 0; $reference['fieldName'] = (string) $attributes->name ?: null; $this->addReferenceMapping($class, $reference, 'one'); } } if (isset($xmlRoot->locale)) { $class->mapLocale(array('fieldName' => (string) $xmlRoot->locale->attributes()->name)); } if (isset($xmlRoot->{'mixed-referrers'})) { foreach ($xmlRoot->{'mixed-referrers'} as $mixedReferrers) { $attributes = $mixedReferrers->attributes(); $mapping = array('fieldName' => (string) $attributes->name, 'referenceType' => isset($attributes['reference-type']) ? strtolower((string) $attributes->{'reference-type'}) : null); $class->mapMixedReferrers($mapping); } } if (isset($xmlRoot->referrers)) { foreach ($xmlRoot->referrers as $referrers) { $attributes = $referrers->attributes(); if (!isset($attributes['referenced-by'])) { throw new MappingException("{$className} is missing the referenced-by attribute for the referrer field " . $attributes->name); } if (!isset($attributes['referring-document'])) { throw new MappingException("{$className} is missing the referring-document attribute for the referrer field " . $attributes->name); } // referenceType is determined from the referencedBy field of referringDocument $mapping = array('fieldName' => (string) $attributes->name, 'cascade' => isset($referrers->cascade) ? $this->getCascadeMode($referrers->cascade) : 0, 'referencedBy' => (string) $attributes->{'referenced-by'}, 'referringDocument' => (string) $attributes->{'referring-document'}); $class->mapReferrers($mapping); } } if (isset($xmlRoot->{'version-name'})) { $class->mapVersionName(array('fieldName' => (string) $xmlRoot->{'version-name'}->attributes()->name)); } if (isset($xmlRoot->{'version-created'})) { $class->mapVersionCreated(array('fieldName' => (string) $xmlRoot->{'version-created'}->attributes()->name)); } if (isset($xmlRoot->{'lifecycle-callbacks'})) { foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) { $class->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\\ODM\\PHPCR\\Event::' . (string) $lifecycleCallback['type'])); } } if (isset($xmlRoot->uuid)) { $mapping = array(); $attributes = $xmlRoot->uuid->attributes(); foreach ($attributes as $key => $value) { $mapping[$key] = (string) $value; } if (!array_key_exists('name', $mapping)) { throw new MappingException(sprintf('Missing name attribute for field of %s', $className)); } $mapping['uuid'] = true; $mapping['fieldName'] = $mapping['name']; $class->mapField($mapping); } $class->validateClassMapping(); }
/** * {@inheritDoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ $element = $this->getElement($className); if ($element['type'] == 'entity') { if (isset($element['repositoryClass'])) { $metadata->setCustomRepositoryClass($element['repositoryClass']); } if (isset($element['readOnly']) && $element['readOnly'] == true) { $metadata->markReadOnly(); } } else { if ($element['type'] == 'mappedSuperclass') { $metadata->setCustomRepositoryClass(isset($element['repositoryClass']) ? $element['repositoryClass'] : null); $metadata->isMappedSuperclass = true; } else { if ($element['type'] == 'embeddable') { $metadata->isEmbeddedClass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } } // Evaluate root level properties $table = array(); if (isset($element['table'])) { $table['name'] = $element['table']; } // Evaluate second level cache if (isset($element['cache'])) { $metadata->enableCache($this->cacheToArray($element['cache'])); } $metadata->setPrimaryTable($table); // Evaluate named queries if (isset($element['namedQueries'])) { foreach ($element['namedQueries'] as $name => $queryMapping) { if (is_string($queryMapping)) { $queryMapping = array('query' => $queryMapping); } if (!isset($queryMapping['name'])) { $queryMapping['name'] = $name; } $metadata->addNamedQuery($queryMapping); } } // Evaluate named native queries if (isset($element['namedNativeQueries'])) { foreach ($element['namedNativeQueries'] as $name => $mappingElement) { if (!isset($mappingElement['name'])) { $mappingElement['name'] = $name; } $metadata->addNamedNativeQuery(array('name' => $mappingElement['name'], 'query' => isset($mappingElement['query']) ? $mappingElement['query'] : null, 'resultClass' => isset($mappingElement['resultClass']) ? $mappingElement['resultClass'] : null, 'resultSetMapping' => isset($mappingElement['resultSetMapping']) ? $mappingElement['resultSetMapping'] : null)); } } // Evaluate sql result set mappings if (isset($element['sqlResultSetMappings'])) { foreach ($element['sqlResultSetMappings'] as $name => $resultSetMapping) { if (!isset($resultSetMapping['name'])) { $resultSetMapping['name'] = $name; } $entities = array(); $columns = array(); if (isset($resultSetMapping['entityResult'])) { foreach ($resultSetMapping['entityResult'] as $entityResultElement) { $entityResult = array('fields' => array(), 'entityClass' => isset($entityResultElement['entityClass']) ? $entityResultElement['entityClass'] : null, 'discriminatorColumn' => isset($entityResultElement['discriminatorColumn']) ? $entityResultElement['discriminatorColumn'] : null); if (isset($entityResultElement['fieldResult'])) { foreach ($entityResultElement['fieldResult'] as $fieldResultElement) { $entityResult['fields'][] = array('name' => isset($fieldResultElement['name']) ? $fieldResultElement['name'] : null, 'column' => isset($fieldResultElement['column']) ? $fieldResultElement['column'] : null); } } $entities[] = $entityResult; } } if (isset($resultSetMapping['columnResult'])) { foreach ($resultSetMapping['columnResult'] as $columnResultAnnot) { $columns[] = array('name' => isset($columnResultAnnot['name']) ? $columnResultAnnot['name'] : null); } } $metadata->addSqlResultSetMapping(array('name' => $resultSetMapping['name'], 'entities' => $entities, 'columns' => $columns)); } } /* not implemented specially anyway. use table = schema.table if (isset($element['schema'])) { $metadata->table['schema'] = $element['schema']; }*/ if (isset($element['inheritanceType'])) { $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType']))); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate discriminatorColumn if (isset($element['discriminatorColumn'])) { $discrColumn = $element['discriminatorColumn']; $metadata->setDiscriminatorColumn(array('name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : null, 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : null, 'columnDefinition' => isset($discrColumn['columnDefinition']) ? (string) $discrColumn['columnDefinition'] : null)); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate discriminatorMap if (isset($element['discriminatorMap'])) { $metadata->setDiscriminatorMap($element['discriminatorMap']); } } } // Evaluate changeTrackingPolicy if (isset($element['changeTrackingPolicy'])) { $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy']))); } // Evaluate indexes if (isset($element['indexes'])) { foreach ($element['indexes'] as $name => $indexYml) { if (!isset($indexYml['name'])) { $indexYml['name'] = $name; } if (is_string($indexYml['columns'])) { $index = array('columns' => array_map('trim', explode(',', $indexYml['columns']))); } else { $index = array('columns' => $indexYml['columns']); } if (isset($indexYml['flags'])) { if (is_string($indexYml['flags'])) { $index['flags'] = array_map('trim', explode(',', $indexYml['flags'])); } else { $index['flags'] = $indexYml['flags']; } } if (isset($indexYml['options'])) { $index['options'] = $indexYml['options']; } $metadata->table['indexes'][$indexYml['name']] = $index; } } // Evaluate uniqueConstraints if (isset($element['uniqueConstraints'])) { foreach ($element['uniqueConstraints'] as $name => $uniqueYml) { if (!isset($uniqueYml['name'])) { $uniqueYml['name'] = $name; } if (is_string($uniqueYml['columns'])) { $unique = array('columns' => array_map('trim', explode(',', $uniqueYml['columns']))); } else { $unique = array('columns' => $uniqueYml['columns']); } if (isset($uniqueYml['options'])) { $unique['options'] = $uniqueYml['options']; } $metadata->table['uniqueConstraints'][$uniqueYml['name']] = $unique; } } if (isset($element['options'])) { $metadata->table['options'] = $element['options']; } $associationIds = array(); if (isset($element['id'])) { // Evaluate identifier settings foreach ($element['id'] as $name => $idElement) { if (isset($idElement['associationKey']) && $idElement['associationKey'] == true) { $associationIds[$name] = true; continue; } $mapping = array('id' => true, 'fieldName' => $name); if (isset($idElement['type'])) { $mapping['type'] = $idElement['type']; } if (isset($idElement['column'])) { $mapping['columnName'] = $idElement['column']; } if (isset($idElement['length'])) { $mapping['length'] = $idElement['length']; } if (isset($idElement['columnDefinition'])) { $mapping['columnDefinition'] = $idElement['columnDefinition']; } if (isset($idElement['options'])) { $mapping['options'] = $idElement['options']; } $metadata->mapField($mapping); if (isset($idElement['generator'])) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . strtoupper($idElement['generator']['strategy']))); } // Check for SequenceGenerator/TableGenerator definition if (isset($idElement['sequenceGenerator'])) { $metadata->setSequenceGeneratorDefinition($idElement['sequenceGenerator']); } else { if (isset($idElement['customIdGenerator'])) { $customGenerator = $idElement['customIdGenerator']; $metadata->setCustomGeneratorDefinition(array('class' => (string) $customGenerator['class'])); } else { if (isset($idElement['tableGenerator'])) { throw MappingException::tableIdGeneratorNotImplemented($className); } } } } } // Evaluate fields if (isset($element['fields'])) { foreach ($element['fields'] as $name => $fieldMapping) { $mapping = $this->columnToArray($name, $fieldMapping); if (isset($fieldMapping['id'])) { $mapping['id'] = true; if (isset($fieldMapping['generator']['strategy'])) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . strtoupper($fieldMapping['generator']['strategy']))); } } if (isset($mapping['version'])) { $metadata->setVersionMapping($mapping); unset($mapping['version']); } $metadata->mapField($mapping); } } if (isset($element['embedded'])) { foreach ($element['embedded'] as $name => $embeddedMapping) { $mapping = array('fieldName' => $name, 'class' => $embeddedMapping['class'], 'columnPrefix' => isset($embeddedMapping['columnPrefix']) ? $embeddedMapping['columnPrefix'] : null); $metadata->mapEmbedded($mapping); } } // Evaluate oneToOne relationships if (isset($element['oneToOne'])) { foreach ($element['oneToOne'] as $name => $oneToOneElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $oneToOneElement['targetEntity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($oneToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $oneToOneElement['fetch']); } if (isset($oneToOneElement['mappedBy'])) { $mapping['mappedBy'] = $oneToOneElement['mappedBy']; } else { if (isset($oneToOneElement['inversedBy'])) { $mapping['inversedBy'] = $oneToOneElement['inversedBy']; } $joinColumns = array(); if (isset($oneToOneElement['joinColumn'])) { $joinColumns[] = $this->joinColumnToArray($oneToOneElement['joinColumn']); } else { if (isset($oneToOneElement['joinColumns'])) { foreach ($oneToOneElement['joinColumns'] as $joinColumnName => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; } if (isset($oneToOneElement['cascade'])) { $mapping['cascade'] = $oneToOneElement['cascade']; } if (isset($oneToOneElement['orphanRemoval'])) { $mapping['orphanRemoval'] = (bool) $oneToOneElement['orphanRemoval']; } $metadata->mapOneToOne($mapping); // Evaluate second level cache if (isset($oneToOneElement['cache'])) { $metadata->enableAssociationCache($mapping['fieldName'], $this->cacheToArray($oneToOneElement['cache'])); } } } // Evaluate oneToMany relationships if (isset($element['oneToMany'])) { foreach ($element['oneToMany'] as $name => $oneToManyElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $oneToManyElement['targetEntity'], 'mappedBy' => $oneToManyElement['mappedBy']); if (isset($oneToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $oneToManyElement['fetch']); } if (isset($oneToManyElement['cascade'])) { $mapping['cascade'] = $oneToManyElement['cascade']; } if (isset($oneToManyElement['orphanRemoval'])) { $mapping['orphanRemoval'] = (bool) $oneToManyElement['orphanRemoval']; } if (isset($oneToManyElement['orderBy'])) { $mapping['orderBy'] = $oneToManyElement['orderBy']; } if (isset($oneToManyElement['indexBy'])) { $mapping['indexBy'] = $oneToManyElement['indexBy']; } $metadata->mapOneToMany($mapping); // Evaluate second level cache if (isset($oneToManyElement['cache'])) { $metadata->enableAssociationCache($mapping['fieldName'], $this->cacheToArray($oneToManyElement['cache'])); } } } // Evaluate manyToOne relationships if (isset($element['manyToOne'])) { foreach ($element['manyToOne'] as $name => $manyToOneElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $manyToOneElement['targetEntity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($manyToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $manyToOneElement['fetch']); } if (isset($manyToOneElement['inversedBy'])) { $mapping['inversedBy'] = $manyToOneElement['inversedBy']; } $joinColumns = array(); if (isset($manyToOneElement['joinColumn'])) { $joinColumns[] = $this->joinColumnToArray($manyToOneElement['joinColumn']); } else { if (isset($manyToOneElement['joinColumns'])) { foreach ($manyToOneElement['joinColumns'] as $joinColumnName => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; if (isset($manyToOneElement['cascade'])) { $mapping['cascade'] = $manyToOneElement['cascade']; } $metadata->mapManyToOne($mapping); // Evaluate second level cache if (isset($manyToOneElement['cache'])) { $metadata->enableAssociationCache($mapping['fieldName'], $this->cacheToArray($manyToOneElement['cache'])); } } } // Evaluate manyToMany relationships if (isset($element['manyToMany'])) { foreach ($element['manyToMany'] as $name => $manyToManyElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $manyToManyElement['targetEntity']); if (isset($manyToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $manyToManyElement['fetch']); } if (isset($manyToManyElement['mappedBy'])) { $mapping['mappedBy'] = $manyToManyElement['mappedBy']; } else { if (isset($manyToManyElement['joinTable'])) { $joinTableElement = $manyToManyElement['joinTable']; $joinTable = array('name' => $joinTableElement['name']); if (isset($joinTableElement['schema'])) { $joinTable['schema'] = $joinTableElement['schema']; } if (isset($joinTableElement['joinColumns'])) { foreach ($joinTableElement['joinColumns'] as $joinColumnName => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } } $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); } if (isset($joinTableElement['inverseJoinColumns'])) { foreach ($joinTableElement['inverseJoinColumns'] as $joinColumnName => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $joinColumnName; } } $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); } $mapping['joinTable'] = $joinTable; } } if (isset($manyToManyElement['inversedBy'])) { $mapping['inversedBy'] = $manyToManyElement['inversedBy']; } if (isset($manyToManyElement['cascade'])) { $mapping['cascade'] = $manyToManyElement['cascade']; } if (isset($manyToManyElement['orderBy'])) { $mapping['orderBy'] = $manyToManyElement['orderBy']; } if (isset($manyToManyElement['indexBy'])) { $mapping['indexBy'] = $manyToManyElement['indexBy']; } if (isset($manyToManyElement['orphanRemoval'])) { $mapping['orphanRemoval'] = (bool) $manyToManyElement['orphanRemoval']; } $metadata->mapManyToMany($mapping); // Evaluate second level cache if (isset($manyToManyElement['cache'])) { $metadata->enableAssociationCache($mapping['fieldName'], $this->cacheToArray($manyToManyElement['cache'])); } } } // Evaluate associationOverride if (isset($element['associationOverride']) && is_array($element['associationOverride'])) { foreach ($element['associationOverride'] as $fieldName => $associationOverrideElement) { $override = array(); // Check for joinColumn if (isset($associationOverrideElement['joinColumn'])) { $joinColumns = array(); foreach ($associationOverrideElement['joinColumn'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } $override['joinColumns'] = $joinColumns; } // Check for joinTable if (isset($associationOverrideElement['joinTable'])) { $joinTableElement = $associationOverrideElement['joinTable']; $joinTable = array('name' => $joinTableElement['name']); if (isset($joinTableElement['schema'])) { $joinTable['schema'] = $joinTableElement['schema']; } foreach ($joinTableElement['joinColumns'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); } foreach ($joinTableElement['inverseJoinColumns'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); } $override['joinTable'] = $joinTable; } $metadata->setAssociationOverride($fieldName, $override); } } // Evaluate associationOverride if (isset($element['attributeOverride']) && is_array($element['attributeOverride'])) { foreach ($element['attributeOverride'] as $fieldName => $attributeOverrideElement) { $mapping = $this->columnToArray($fieldName, $attributeOverrideElement); $metadata->setAttributeOverride($fieldName, $mapping); } } // Evaluate lifeCycleCallbacks if (isset($element['lifecycleCallbacks'])) { foreach ($element['lifecycleCallbacks'] as $type => $methods) { foreach ($methods as $method) { $metadata->addLifecycleCallback($method, constant('Doctrine\\ORM\\Events::' . $type)); } } } // Evaluate entityListeners if (isset($element['entityListeners'])) { foreach ($element['entityListeners'] as $className => $entityListener) { // Evaluate the listener using naming convention. if (empty($entityListener)) { EntityListenerBuilder::bindEntityListener($metadata, $className); continue; } foreach ($entityListener as $eventName => $callbackElement) { foreach ($callbackElement as $methodName) { $metadata->addEntityListener($eventName, $className, $methodName); } } } } }
private function addReferenceMapping(ClassMetadata $class, $reference, $type) { $attributes = $reference->attributes(); $class->mapField(array('type' => $type, 'reference' => true, 'targetDocument' => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null, 'name' => (string) $attributes['field'])); }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $reflClass = $metadata->getReflectionClass(); $documentAnnots = array(); foreach ($this->reader->getClassAnnotations($reflClass) as $annot) { foreach ($this->entityAnnotationClasses as $annotClass => $i) { if ($annot instanceof $annotClass) { $documentAnnots[$i] = $annot; } } } if (!$documentAnnots) { throw MappingException::classIsNotAValidDocument($className); } // find the winning document annotation ksort($documentAnnots); $documentAnnot = reset($documentAnnots); if (isset($documentAnnot->versionable) && $documentAnnot->versionable) { $metadata->setVersioned($documentAnnot->versionable); } $metadata->setNodeType($documentAnnot->nodeType); if (isset($documentAnnot->referenceable) && $documentAnnot->referenceable) { $metadata->setReferenceable(true); } if ($documentAnnot->repositoryClass) { $metadata->setCustomRepositoryClassName($documentAnnot->repositoryClass); } if ($documentAnnot->translator) { $metadata->setTranslator($documentAnnot->translator); } foreach ($reflClass->getProperties() as $property) { if ($metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->name) && $metadata->name !== $property->getDeclaringClass()->getName()) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) { if ($fieldAnnot instanceof ODM\Property) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapField($mapping); } elseif ($fieldAnnot instanceof ODM\Id) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapId($mapping); } elseif ($fieldAnnot instanceof ODM\Node) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapNode($mapping); } elseif ($fieldAnnot instanceof ODM\Nodename) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapNodename($mapping); } elseif ($fieldAnnot instanceof ODM\ParentDocument) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapParentDocument($mapping); } elseif ($fieldAnnot instanceof ODM\Child) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapChild($mapping); } elseif ($fieldAnnot instanceof ODM\Children) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapChildren($mapping); } elseif ($fieldAnnot instanceof ODM\ReferenceOne) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapManyToOne($mapping); } elseif ($fieldAnnot instanceof ODM\ReferenceMany) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapManyToMany($mapping); } elseif ($fieldAnnot instanceof ODM\Referrers) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapReferrers($mapping); } elseif ($fieldAnnot instanceof ODM\Locale) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapLocale($mapping); } elseif ($fieldAnnot instanceof ODM\VersionName) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapVersionName($mapping); } elseif ($fieldAnnot instanceof ODM\VersionCreated) { $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapVersionCreated($mapping); } if (!isset($mapping['name'])) { $mapping['name'] = $property->getName(); } } } foreach ($reflClass->getMethods() as $method) { if ($method->isPublic() && $method->getDeclaringClass()->getName() == $metadata->name) { foreach ($this->reader->getMethodAnnotations($method) as $annot) { if ($annot instanceof ODM\PrePersist) { $metadata->addLifecycleCallback($method->getName(), Event::prePersist); } elseif ($annot instanceof ODM\PostPersist) { $metadata->addLifecycleCallback($method->getName(), Event::postPersist); } elseif ($annot instanceof ODM\PreUpdate) { $metadata->addLifecycleCallback($method->getName(), Event::preUpdate); } elseif ($annot instanceof ODM\PostUpdate) { $metadata->addLifecycleCallback($method->getName(), Event::postUpdate); } elseif ($annot instanceof ODM\PreRemove) { $metadata->addLifecycleCallback($method->getName(), Event::preRemove); } elseif ($annot instanceof ODM\PostRemove) { $metadata->addLifecycleCallback($method->getName(), Event::postRemove); } elseif ($annot instanceof ODM\PreLoad) { $metadata->addLifecycleCallback($method->getName(), Event::preLoad); } elseif ($annot instanceof ODM\PostLoad) { $metadata->addLifecycleCallback($method->getName(), Event::postLoad); } } } } // Check there is a @Locale annotation for translatable documents if (count($metadata->translatableFields)) { if (!isset($metadata->localeMapping)) { throw new MappingException("You must define a @Locale field for translatable document '{$className}'"); } } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata */ public function loadMetadataForClass($className, ClassMetadata $metadata) { global $container; $builder = new ClassMetadataBuilder($metadata); $tableName = static::classToTableName($className); $this->loadDataContainer($tableName); try { /** @var ClassLoader $entitiesClassLoader */ $entitiesClassLoader = $container['doctrine.orm.entitiesClassLoader']; if (!class_exists($className, false)) { $entitiesClassLoader->loadClass($className); } if (class_exists($className, false)) { $class = new \ReflectionClass($className); } else { $class = false; } } catch (\Exception $e) { $class = false; } if (!array_key_exists('TL_DCA', $GLOBALS)) { $GLOBALS['TL_DCA'] = array(); } if (!array_key_exists($tableName, $GLOBALS['TL_DCA']) || !is_array($GLOBALS['TL_DCA'][$tableName])) { $GLOBALS['TL_DCA'][$tableName] = array('fields' => array()); } $entityConfig = array(); if (array_key_exists('entity', $GLOBALS['TL_DCA'][$tableName])) { $entityConfig = $GLOBALS['TL_DCA'][$tableName]['entity']; } if ($class && !$class->isInstantiable()) { $metadata->isMappedSuperclass = true; } elseif (array_key_exists('isMappedSuperclass', $entityConfig)) { $metadata->isMappedSuperclass = $entityConfig['isMappedSuperclass']; } // custom repository class if (array_key_exists('repositoryClass', $entityConfig)) { $metadata->setCustomRepositoryClass($entityConfig['repositoryClass']); } else { $metadata->setCustomRepositoryClass('Contao\\Doctrine\\ORM\\Repository'); } // id generator if (array_key_exists('idGenerator', $entityConfig)) { $metadata->setIdGeneratorType($entityConfig['idGenerator']); } else { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } // indexes if (isset($entityConfig['indexes'])) { if (is_array($entityConfig['indexes'])) { foreach ($entityConfig['indexes'] as $name => $columns) { if (is_array($columns)) { $builder->addIndex($columns, $name); } else { throw new \RuntimeException(sprintf('$GLOBALS[TL_DCA][%s][entity][indexes][%s] must be an array', $tableName, $name)); } } } else { throw new \RuntimeException(sprintf('$GLOBALS[TL_DCA][%s][entity][indexes] must be an array', $tableName)); } } // uniques if (isset($entityConfig['uniques'])) { if (is_array($entityConfig['uniques'])) { foreach ($entityConfig['uniques'] as $name => $columns) { if (is_array($columns)) { $builder->addUniqueConstraint($columns, $name); } else { throw new \RuntimeException(sprintf('$GLOBALS[TL_DCA][%s][entity][uniques][%s] must be an array', $tableName, $name)); } } } else { throw new \RuntimeException(sprintf('$GLOBALS[TL_DCA][%s][entity][uniques] must be an array', $tableName)); } } $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable(array('name' => $tableName)); $fields = (array) $GLOBALS['TL_DCA'][$tableName]['fields']; foreach ($fields as $fieldName => $fieldConfig) { $configured = array_key_exists('field', $fieldConfig) || array_key_exists('oneToOne', $fieldConfig) || array_key_exists('oneToMany', $fieldConfig) || array_key_exists('manyToOne', $fieldConfig) || array_key_exists('manyToMany', $fieldConfig); if (!$configured && empty($fieldConfig['inputType']) || $configured && $fieldConfig['field'] === false) { continue; } if (isset($fieldConfig['oneToOne'])) { $fieldConfig['oneToOne']['fieldName'] = $fieldName; $metadata->mapOneToOne($fieldConfig['oneToOne']); } elseif (isset($fieldConfig['oneToMany'])) { $fieldConfig['oneToMany']['fieldName'] = $fieldName; $metadata->mapOneToMany($fieldConfig['oneToMany']); } elseif (isset($fieldConfig['manyToOne'])) { $fieldConfig['manyToOne']['fieldName'] = $fieldName; $metadata->mapManyToOne($fieldConfig['manyToOne']); } elseif (isset($fieldConfig['manyToMany'])) { $fieldConfig['manyToMany']['fieldName'] = $fieldName; $metadata->mapManyToMany($fieldConfig['manyToMany']); } else { $fieldMapping = array(); $inputTypes = array($fieldConfig['inputType']); $inputTypeOptions = array(); if ($fieldConfig['foreignKey']) { $inputTypeOptions[] = 'foreignKey'; } if ($fieldConfig['eval']['multiple']) { $inputTypeOptions[] = 'multiple'; } for ($i = 0; $i < count($inputTypeOptions); $i++) { $inputTypeOption = $fieldConfig['inputType'] . '_' . $inputTypeOptions[$i]; array_unshift($inputTypes, $inputTypeOption); for ($j = $i + 1; $j < count($inputTypeOptions); $j++) { $inputTypeOption .= '_' . $inputTypeOptions[$j]; array_unshift($inputTypes, $inputTypeOption); } } foreach ($inputTypes as $inputType) { if (array_key_exists($inputType, $GLOBALS['DOCTRINE_TYPE_MAP'])) { $fieldMapping = $GLOBALS['DOCTRINE_TYPE_MAP'][$inputType]; break; } } if (isset($fieldConfig['eval']['maxlength'])) { $fieldMapping['length'] = (int) $fieldConfig['eval']['maxlength']; } if (isset($fieldConfig['eval']['unique'])) { $fieldMapping['unique'] = (bool) $fieldConfig['eval']['unique']; } if (array_key_exists('field', $fieldConfig)) { $fieldMapping = array_merge($fieldMapping, $fieldConfig['field']); } $fieldMapping['fieldName'] = $fieldName; $metadata->mapField($fieldMapping); } } /* if (TL_MODE == 'BE' && !$metadata->isMappedSuperclass) { EntityGeneration::generateEntity($metadata); } */ }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $class) { $reflClass = $class->getReflectionClass(); $isValidDocument = false; $classAnnotations = $this->reader->getClassAnnotations($reflClass); foreach ($classAnnotations as $classAnnotation) { if ($classAnnotation instanceof ODM\Document) { if ($classAnnotation->indexed) { $class->indexed = true; } $class->setCustomRepositoryClass($classAnnotation->repositoryClass); $isValidDocument = true; } elseif ($classAnnotation instanceof ODM\EmbeddedDocument) { $class->isEmbeddedDocument = true; $isValidDocument = true; } else { if ($classAnnotation instanceof ODM\MappedSuperclass) { $class->isMappedSuperclass = true; $isValidDocument = true; } else { if ($classAnnotation instanceof ODM\Index) { $class->indexed = true; } else { if ($classAnnotation instanceof ODM\InheritanceRoot) { $class->markInheritanceRoot(); } } } } } if (!$isValidDocument) { throw MappingException::classIsNotAValidDocument($className); } foreach ($reflClass->getProperties() as $property) { if ($class->isInheritedAssociation($property->name) || $class->isInheritedField($property->name)) { continue; } $mapping = array(); $mapping['fieldName'] = $property->name; if ($this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\CouchDB\\Mapping\\Annotations\\Index')) { $mapping['indexed'] = true; } foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) { if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\Field) { if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\Version) { $mapping['isVersionField'] = true; } $mapping = array_merge($mapping, (array) $fieldAnnot); unset($mapping['value']); $class->mapField($mapping); } else { if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\ReferenceOne) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); unset($mapping['value']); $class->mapManyToOne($mapping); } else { if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\ReferenceMany) { $mapping = array_merge($mapping, (array) $fieldAnnot); $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade); unset($mapping['value']); $class->mapManyToMany($mapping); } else { if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\Attachments) { $class->mapAttachments($mapping['fieldName']); } else { if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\EmbedOne || $fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Annotations\EmbedMany) { $mapping = array_merge($mapping, (array) $fieldAnnot); unset($mapping['value']); $class->mapEmbedded($mapping); } } } } } } } }
/** * {@inheritDoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ $class = $metadata->getReflectionClass(); if (!$class) { // this happens when running annotation driver in combination with // static reflection services. This is not the nicest fix $class = new \ReflectionClass($metadata->name); } $classAnnotations = $this->reader->getClassAnnotations($class); if ($classAnnotations) { foreach ($classAnnotations as $key => $annot) { if (!is_numeric($key)) { continue; } $classAnnotations[get_class($annot)] = $annot; } } // Evaluate Entity annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Entity'])) { $entityAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Entity']; if ($entityAnnot->repositoryClass !== null) { $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass); } if ($entityAnnot->readOnly) { $metadata->markReadOnly(); } } else { if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass'])) { $mappedSuperclassAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass']; $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass); $metadata->isMappedSuperclass = true; } else { if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Embeddable'])) { $metadata->isEmbeddedClass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } } // Evaluate Table annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Table'])) { $tableAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Table']; $primaryTable = array('name' => $tableAnnot->name, 'schema' => $tableAnnot->schema); if ($tableAnnot->indexes !== null) { foreach ($tableAnnot->indexes as $indexAnnot) { $index = array('columns' => $indexAnnot->columns); if (!empty($indexAnnot->flags)) { $index['flags'] = $indexAnnot->flags; } if (!empty($indexAnnot->options)) { $index['options'] = $indexAnnot->options; } if (!empty($indexAnnot->name)) { $primaryTable['indexes'][$indexAnnot->name] = $index; } else { $primaryTable['indexes'][] = $index; } } } if ($tableAnnot->uniqueConstraints !== null) { foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { $uniqueConstraint = array('columns' => $uniqueConstraintAnnot->columns); if (!empty($uniqueConstraintAnnot->options)) { $uniqueConstraint['options'] = $uniqueConstraintAnnot->options; } if (!empty($uniqueConstraintAnnot->name)) { $primaryTable['uniqueConstraints'][$uniqueConstraintAnnot->name] = $uniqueConstraint; } else { $primaryTable['uniqueConstraints'][] = $uniqueConstraint; } } } if ($tableAnnot->options) { $primaryTable['options'] = $tableAnnot->options; } $metadata->setPrimaryTable($primaryTable); } // Evaluate @Cache annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Cache'])) { $cacheAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Cache']; $cacheMap = array('region' => $cacheAnnot->region, 'usage' => constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage)); $metadata->enableCache($cacheMap); } // Evaluate NamedNativeQueries annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\NamedNativeQueries'])) { $namedNativeQueriesAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\NamedNativeQueries']; foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) { $metadata->addNamedNativeQuery(array('name' => $namedNativeQuery->name, 'query' => $namedNativeQuery->query, 'resultClass' => $namedNativeQuery->resultClass, 'resultSetMapping' => $namedNativeQuery->resultSetMapping)); } } // Evaluate SqlResultSetMappings annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\SqlResultSetMappings'])) { $sqlResultSetMappingsAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\SqlResultSetMappings']; foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) { $entities = array(); $columns = array(); foreach ($resultSetMapping->entities as $entityResultAnnot) { $entityResult = array('fields' => array(), 'entityClass' => $entityResultAnnot->entityClass, 'discriminatorColumn' => $entityResultAnnot->discriminatorColumn); foreach ($entityResultAnnot->fields as $fieldResultAnnot) { $entityResult['fields'][] = array('name' => $fieldResultAnnot->name, 'column' => $fieldResultAnnot->column); } $entities[] = $entityResult; } foreach ($resultSetMapping->columns as $columnResultAnnot) { $columns[] = array('name' => $columnResultAnnot->name); } $metadata->addSqlResultSetMapping(array('name' => $resultSetMapping->name, 'entities' => $entities, 'columns' => $columns)); } } // Evaluate NamedQueries annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries'])) { $namedQueriesAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries']; if (!is_array($namedQueriesAnnot->value)) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } foreach ($namedQueriesAnnot->value as $namedQuery) { if (!$namedQuery instanceof \Doctrine\ORM\Mapping\NamedQuery) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } $metadata->addNamedQuery(array('name' => $namedQuery->name, 'query' => $namedQuery->query)); } } // Evaluate InheritanceType annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType'])) { $inheritanceTypeAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType']; $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value)); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate DiscriminatorColumn annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn'])) { $discrColumnAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn']; $metadata->setDiscriminatorColumn(array('name' => $discrColumnAnnot->name, 'type' => $discrColumnAnnot->type ?: 'string', 'length' => $discrColumnAnnot->length ?: 255, 'columnDefinition' => $discrColumnAnnot->columnDefinition)); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate DiscriminatorMap annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap'])) { $discrMapAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap']; $metadata->setDiscriminatorMap($discrMapAnnot->value); } } } // Evaluate DoctrineChangeTrackingPolicy annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy'])) { $changeTrackingAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy']; $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); } // Evaluate annotations on properties/fields /* @var $property \ReflectionProperty */ foreach ($class->getProperties() as $property) { if ($metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->name) || $metadata->isInheritedAssociation($property->name) || $metadata->isInheritedEmbeddedClass($property->name)) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); // Evaluate @Cache annotation if (($cacheAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Cache')) !== null) { $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], array('usage' => constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage), 'region' => $cacheAnnot->region)); } // Check for JoinColumn/JoinColumns annotations $joinColumns = array(); if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinColumn')) { $joinColumns[] = $this->joinColumnToArray($joinColumnAnnot); } else { if ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinColumns')) { foreach ($joinColumnsAnnot->value as $joinColumn) { $joinColumns[] = $this->joinColumnToArray($joinColumn); } } } // Field can only be annotated with one of: // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany if ($columnAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Column')) { if ($columnAnnot->type == null) { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } $mapping = $this->columnToArray($property->getName(), $columnAnnot); if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\GeneratedValue')) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy)); } if ($this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Version')) { $metadata->setVersionMapping($mapping); } $metadata->mapField($mapping); // Check for SequenceGenerator/TableGenerator definition if ($seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\SequenceGenerator')) { $metadata->setSequenceGeneratorDefinition(array('sequenceName' => $seqGeneratorAnnot->sequenceName, 'allocationSize' => $seqGeneratorAnnot->allocationSize, 'initialValue' => $seqGeneratorAnnot->initialValue)); } else { if ($this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\TableGenerator')) { throw MappingException::tableIdGeneratorNotImplemented($className); } else { if ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\CustomIdGenerator')) { $metadata->setCustomGeneratorDefinition(array('class' => $customGeneratorAnnot->class)); } } } } else { if ($oneToOneAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToOne')) { if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } $mapping['targetEntity'] = $oneToOneAnnot->targetEntity; $mapping['joinColumns'] = $joinColumns; $mapping['mappedBy'] = $oneToOneAnnot->mappedBy; $mapping['inversedBy'] = $oneToOneAnnot->inversedBy; $mapping['cascade'] = $oneToOneAnnot->cascade; $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnot->fetch); $metadata->mapOneToOne($mapping); } else { if ($oneToManyAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToMany')) { $mapping['mappedBy'] = $oneToManyAnnot->mappedBy; $mapping['targetEntity'] = $oneToManyAnnot->targetEntity; $mapping['cascade'] = $oneToManyAnnot->cascade; $mapping['indexBy'] = $oneToManyAnnot->indexBy; $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnot->fetch); if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapOneToMany($mapping); } else { if ($manyToOneAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToOne')) { if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } $mapping['joinColumns'] = $joinColumns; $mapping['cascade'] = $manyToOneAnnot->cascade; $mapping['inversedBy'] = $manyToOneAnnot->inversedBy; $mapping['targetEntity'] = $manyToOneAnnot->targetEntity; $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); $metadata->mapManyToOne($mapping); } else { if ($manyToManyAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToMany')) { $joinTable = array(); if ($joinTableAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinTable')) { $joinTable = array('name' => $joinTableAnnot->name, 'schema' => $joinTableAnnot->schema); foreach ($joinTableAnnot->joinColumns as $joinColumn) { $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn); } foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn); } } $mapping['joinTable'] = $joinTable; $mapping['targetEntity'] = $manyToManyAnnot->targetEntity; $mapping['mappedBy'] = $manyToManyAnnot->mappedBy; $mapping['inversedBy'] = $manyToManyAnnot->inversedBy; $mapping['cascade'] = $manyToManyAnnot->cascade; $mapping['indexBy'] = $manyToManyAnnot->indexBy; $mapping['orphanRemoval'] = $manyToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnot->fetch); if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapManyToMany($mapping); } else { if ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Embedded')) { $mapping['class'] = $embeddedAnnot->class; $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix; $metadata->mapEmbedded($mapping); } } } } } } } // Evaluate AssociationOverrides annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\AssociationOverrides'])) { $associationOverridesAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\AssociationOverrides']; foreach ($associationOverridesAnnot->value as $associationOverride) { $override = array(); $fieldName = $associationOverride->name; // Check for JoinColumn/JoinColumns annotations if ($associationOverride->joinColumns) { $joinColumns = array(); foreach ($associationOverride->joinColumns as $joinColumn) { $joinColumns[] = $this->joinColumnToArray($joinColumn); } $override['joinColumns'] = $joinColumns; } // Check for JoinTable annotations if ($associationOverride->joinTable) { $joinTableAnnot = $associationOverride->joinTable; $joinTable = array('name' => $joinTableAnnot->name, 'schema' => $joinTableAnnot->schema); foreach ($joinTableAnnot->joinColumns as $joinColumn) { $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn); } foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn); } $override['joinTable'] = $joinTable; } // Check for inversedBy if ($associationOverride->inversedBy) { $override['inversedBy'] = $associationOverride->inversedBy; } $metadata->setAssociationOverride($fieldName, $override); } } // Evaluate AttributeOverrides annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\AttributeOverrides'])) { $attributeOverridesAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\AttributeOverrides']; foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) { $attributeOverride = $this->columnToArray($attributeOverrideAnnot->name, $attributeOverrideAnnot->column); $metadata->setAttributeOverride($attributeOverrideAnnot->name, $attributeOverride); } } // Evaluate EntityListeners annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\EntityListeners'])) { $entityListenersAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\EntityListeners']; foreach ($entityListenersAnnot->value as $item) { $listenerClassName = $metadata->fullyQualifiedClassName($item); if (!class_exists($listenerClassName)) { throw MappingException::entityListenerClassNotFound($listenerClassName, $className); } $hasMapping = false; $listenerClass = new \ReflectionClass($listenerClassName); /* @var $method \ReflectionMethod */ foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { // find method callbacks. $callbacks = $this->getMethodCallbacks($method); $hasMapping = $hasMapping ?: !empty($callbacks); foreach ($callbacks as $value) { $metadata->addEntityListener($value[1], $listenerClassName, $value[0]); } } // Evaluate the listener using naming convention. if (!$hasMapping) { EntityListenerBuilder::bindEntityListener($metadata, $listenerClassName); } } } // Evaluate @HasLifecycleCallbacks annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\HasLifecycleCallbacks'])) { /* @var $method \ReflectionMethod */ foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { foreach ($this->getMethodCallbacks($method) as $value) { $metadata->addLifecycleCallback($value[0], $value[1]); } } } }
/** * {@inheritDoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $this->reverseEngineerMappingFromDatabase(); if (!isset($this->classToTableNames[$className])) { throw new \InvalidArgumentException("Unknown class " . $className); } $tableName = $this->classToTableNames[$className]; $metadata->name = $className; $metadata->table['name'] = $tableName; $columns = $this->tables[$tableName]->getColumns(); $indexes = $this->tables[$tableName]->getIndexes(); try { $primaryKeyColumns = $this->tables[$tableName]->getPrimaryKey()->getColumns(); } catch(SchemaException $e) { $primaryKeyColumns = array(); } if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) { $foreignKeys = $this->tables[$tableName]->getForeignKeys(); } else { $foreignKeys = array(); } $allForeignKeyColumns = array(); foreach ($foreignKeys as $foreignKey) { $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns()); } $ids = array(); $fieldMappings = array(); foreach ($columns as $column) { $fieldMapping = array(); if (in_array($column->getName(), $allForeignKeyColumns)) { continue; } else if ($primaryKeyColumns && in_array($column->getName(), $primaryKeyColumns)) { $fieldMapping['id'] = true; } $fieldMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $column->getName(), false); $fieldMapping['columnName'] = $column->getName(); $fieldMapping['type'] = strtolower((string) $column->getType()); if ($column->getType() instanceof \Doctrine\DBAL\Types\StringType) { $fieldMapping['length'] = $column->getLength(); $fieldMapping['fixed'] = $column->getFixed(); } else if ($column->getType() instanceof \Doctrine\DBAL\Types\IntegerType) { $fieldMapping['unsigned'] = $column->getUnsigned(); } $fieldMapping['nullable'] = $column->getNotNull() ? false : true; if (isset($fieldMapping['id'])) { $ids[] = $fieldMapping; } else { $fieldMappings[] = $fieldMapping; } } if ($ids) { // We need to check for the columns here, because we might have associations as id as well. if (count($primaryKeyColumns) == 1) { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } foreach ($ids as $id) { $metadata->mapField($id); } } foreach ($fieldMappings as $fieldMapping) { $metadata->mapField($fieldMapping); } foreach ($this->manyToManyTables as $manyTable) { foreach ($manyTable->getForeignKeys() as $foreignKey) { // foreign key maps to the table of the current entity, many to many association probably exists if (strtolower($tableName) == strtolower($foreignKey->getForeignTableName())) { $myFk = $foreignKey; $otherFk = null; foreach ($manyTable->getForeignKeys() as $foreignKey) { if ($foreignKey != $myFk) { $otherFk = $foreignKey; break; } } if (!$otherFk) { // the definition of this many to many table does not contain // enough foreign key information to continue reverse engineering. continue; } $localColumn = current($myFk->getColumns()); $associationMapping = array(); $associationMapping['fieldName'] = $this->getFieldNameForColumn($manyTable->getName(), current($otherFk->getColumns()), true); $associationMapping['targetEntity'] = $this->getClassNameForTable($otherFk->getForeignTableName()); if (current($manyTable->getColumns())->getName() == $localColumn) { $associationMapping['inversedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true); $associationMapping['joinTable'] = array( 'name' => strtolower($manyTable->getName()), 'joinColumns' => array(), 'inverseJoinColumns' => array(), ); $fkCols = $myFk->getForeignColumns(); $cols = $myFk->getColumns(); for ($i = 0; $i < count($cols); $i++) { $associationMapping['joinTable']['joinColumns'][] = array( 'name' => $cols[$i], 'referencedColumnName' => $fkCols[$i], ); } $fkCols = $otherFk->getForeignColumns(); $cols = $otherFk->getColumns(); for ($i = 0; $i < count($cols); $i++) { $associationMapping['joinTable']['inverseJoinColumns'][] = array( 'name' => $cols[$i], 'referencedColumnName' => $fkCols[$i], ); } } else { $associationMapping['mappedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true); } $metadata->mapManyToMany($associationMapping); break; } } } foreach ($foreignKeys as $foreignKey) { $foreignTable = $foreignKey->getForeignTableName(); $cols = $foreignKey->getColumns(); $fkCols = $foreignKey->getForeignColumns(); $localColumn = current($cols); $associationMapping = array(); $associationMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $localColumn, true); $associationMapping['targetEntity'] = $this->getClassNameForTable($foreignTable); if (isset($metadata->fieldMappings[$associationMapping['fieldName']])) { $associationMapping['fieldName'] = $associationMapping['fieldName'] . "2"; } if ($primaryKeyColumns && in_array($localColumn, $primaryKeyColumns)) { $associationMapping['id'] = true; } for ($i = 0; $i < count($cols); $i++) { $associationMapping['joinColumns'][] = array( 'name' => $cols[$i], 'referencedColumnName' => $fkCols[$i], ); } //Here we need to check if $cols are the same as $primaryKeyColumns if (!array_diff($cols,$primaryKeyColumns)) { $metadata->mapOneToOne($associationMapping); } else { $metadata->mapManyToOne($associationMapping); } } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $class) { /** @var $class \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */ try { $element = $this->getElement($className); } catch (DoctrineMappingException $e) { // Convert Exception type for consistency with other drivers throw new MappingException($e->getMessage(), $e->getCode(), $e); } if (!$element) { return; } if ($element['type'] == 'document') { $class->setCustomRepositoryClass(isset($element['repositoryClass']) ? $element['repositoryClass'] : null); if (isset($element['indexed']) && $element['indexed'] == true) { $class->indexed = true; } if (isset($element['inheritanceRoot']) && $element['inheritanceRoot']) { $class->markInheritanceRoot(); } } else { if ($element['type'] == 'embedded') { $class->isEmbeddedDocument = true; if (isset($element['inheritanceRoot']) && $element['inheritanceRoot']) { $class->markInheritanceRoot(); } } else { if (strtolower($element['type']) == "mappedsuperclass") { $class->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidDocument($className); } } } if (isset($element['id'])) { foreach ($element['id'] as $fieldName => $idElement) { $class->mapField(array('fieldName' => $fieldName, 'indexed' => isset($idElement['index']) ? (bool) $idElement['index'] : false, 'type' => isset($idElement['type']) ? $idElement['type'] : null, 'id' => true, 'strategy' => isset($idElement['strategy']) ? $idElement['strategy'] : null)); } } if (isset($element['fields'])) { foreach ($element['fields'] as $fieldName => $fieldElement) { $class->mapField(array('fieldName' => $fieldName, 'jsonName' => isset($fieldElement['jsonName']) ? $fieldElement['jsonName'] : null, 'indexed' => isset($fieldElement['index']) ? (bool) $fieldElement['index'] : false, 'type' => isset($fieldElement['type']) ? $fieldElement['type'] : null, 'isVersionField' => isset($fieldElement['version']) ? true : null)); } } if (isset($element['referenceOne'])) { foreach ($element['referenceOne'] as $field => $referenceOneElement) { $class->mapManyToOne(array('cascade' => isset($referenceOneElement['cascade']) ? $this->getCascadeMode($referenceOneElement['cascade']) : 0, 'targetDocument' => (string) $referenceOneElement['targetDocument'], 'fieldName' => $field, 'jsonName' => isset($referenceOneElement['jsonName']) ? (string) $referenceOneElement['jsonName'] : null, 'indexed' => isset($referenceOneElement['index']) ? (bool) $referenceOneElement['index'] : false)); } } if (isset($element['referenceMany'])) { foreach ($element['referenceMany'] as $field => $referenceManyElement) { $class->mapManyToMany(array('cascade' => isset($referenceManyElement['cascade']) ? $this->getCascadeMode($referenceManyElement['cascade']) : 0, 'targetDocument' => (string) $referenceManyElement['targetDocument'], 'fieldName' => $field, 'jsonName' => isset($referenceManyElement['jsonName']) ? (string) $referenceManyElement['jsonName'] : null, 'mappedBy' => isset($referenceManyElement['mappedBy']) ? (string) $referenceManyElement['mappedBy'] : null)); } } if (isset($element['attachments'])) { $class->mapAttachments($element['attachments']); } if (isset($element['embedOne'])) { foreach ($element['embedOne'] as $field => $embedOneElement) { $class->mapEmbedded(array('targetDocument' => (string) $embedOneElement['targetDocument'], 'fieldName' => $field, 'jsonName' => isset($embedOneElement['jsonName']) ? (string) $embedOneElement['jsonName'] : null, 'embedded' => 'one')); } } if (isset($element['embedMany'])) { foreach ($element['embedMany'] as $field => $embedManyElement) { $class->mapEmbedded(array('targetDocument' => (string) $embedManyElement['targetDocument'], 'fieldName' => $field, 'jsonName' => isset($embedManyElement['jsonName']) ? (string) $embedManyElement['jsonName'] : null, 'embedded' => 'many')); } } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $class) { /** @var $class \Doctrine\ODM\PHPCR\Mapping\ClassMetadata */ try { $element = $this->getElement($className); } catch (DoctrineMappingException $e) { // Convert Exception type for consistency with other drivers throw new MappingException($e->getMessage(), $e->getCode(), $e); } if (!$element) { return; } $element['type'] = isset($element['type']) ? $element['type'] : 'document'; if (isset($element['repositoryClass'])) { $class->setCustomRepositoryClassName($element['repositoryClass']); } if (isset($element['translator'])) { $class->setTranslator($element['translator']); } if (isset($element['versionable']) && $element['versionable']) { $class->setVersioned($element['versionable']); } if (isset($element['referenceable']) && $element['referenceable']) { $class->setReferenceable($element['referenceable']); } if (isset($element['uniqueNodeType']) && $element['uniqueNodeType']) { $class->setUniqueNodeType($element['uniqueNodeType']); } if (isset($element['mixins'])) { $mixins = array(); foreach ($element['mixins'] as $mixin) { $mixins[] = $mixin; } $class->setMixins($mixins); } if (isset($element['inheritMixins'])) { $class->setInheritMixins($element['inheritMixins']); } if (isset($element['nodeType'])) { $class->setNodeType($element['nodeType']); } if ($element['type'] === 'mappedSuperclass') { $class->isMappedSuperclass = true; } if (isset($element['fields'])) { foreach ($element['fields'] as $fieldName => $mapping) { if (is_string($mapping)) { $type = $mapping; $mapping = array(); $mapping['type'] = $type; } if (!isset($mapping['fieldName'])) { $mapping['fieldName'] = $fieldName; } $class->mapField($mapping); } } if (isset($element['uuid'])) { $mapping = array('fieldName' => $element['uuid'], 'uuid' => true); $class->mapField($mapping); } if (isset($element['id'])) { if (is_array($element['id'])) { if (!isset($element['id']['fieldName'])) { throw new MappingException("Missing fieldName property for id field"); } $fieldName = $element['id']['fieldName']; } else { $fieldName = $element['id']; } $mapping = array('fieldName' => $fieldName, 'id' => true); if (isset($element['id']['generator']['strategy'])) { $mapping['strategy'] = $element['id']['generator']['strategy']; } $class->mapId($mapping); } if (isset($element['node'])) { $class->mapNode(array('fieldName' => $element['node'])); } if (isset($element['nodename'])) { $class->mapNodename(array('fieldName' => $element['nodename'])); } if (isset($element['parentdocument'])) { $mapping = array('fieldName' => $element['parentdocument'], 'cascade' => isset($element['cascade']) ? $this->getCascadeMode($element['cascade']) : 0); $class->mapParentDocument($mapping); } if (isset($element['child'])) { foreach ($element['child'] as $fieldName => $mapping) { if (is_string($mapping)) { $name = $mapping; $mapping = array(); $mapping['nodeName'] = $name; } if (!isset($mapping['fieldName'])) { $mapping['fieldName'] = $fieldName; } $mapping['cascade'] = isset($mapping['cascade']) ? $this->getCascadeMode($mapping['cascade']) : 0; $class->mapChild($mapping); } } if (isset($element['children'])) { foreach ($element['children'] as $fieldName => $mapping) { // TODO should we really support this syntax? if (is_string($mapping)) { $filter = $mapping; $mapping = array(); $mapping['filter'] = $filter; } if (!isset($mapping['fieldName'])) { $mapping['fieldName'] = $fieldName; } if (!isset($mapping['filter'])) { $mapping['filter'] = null; } elseif (is_string($mapping['filter'])) { $mapping['filter'] = (array) $mapping['filter']; } if (!isset($mapping['fetchDepth'])) { $mapping['fetchDepth'] = -1; } if (!isset($mapping['ignoreUntranslated'])) { $mapping['ignoreUntranslated'] = false; } $mapping['cascade'] = isset($mapping['cascade']) ? $this->getCascadeMode($mapping['cascade']) : 0; $class->mapChildren($mapping); } } if (isset($element['referenceOne'])) { foreach ($element['referenceOne'] as $fieldName => $reference) { $this->addMappingFromReference($class, $fieldName, $reference, 'one'); } } if (isset($element['referenceMany'])) { foreach ($element['referenceMany'] as $fieldName => $reference) { $this->addMappingFromReference($class, $fieldName, $reference, 'many'); } } if (isset($element['locale'])) { $class->mapLocale(array('fieldName' => $element['locale'])); } if (isset($element['depth'])) { $class->mapDepth(array('fieldName' => $element['depth'])); } if (isset($element['mixedReferrers'])) { foreach ($element['mixedReferrers'] as $name => $attributes) { $mapping = array('fieldName' => $name, 'referenceType' => isset($attributes['referenceType']) ? $attributes['referenceType'] : null); $class->mapMixedReferrers($mapping); } } if (isset($element['referrers'])) { foreach ($element['referrers'] as $name => $attributes) { if (!isset($attributes['referencedBy'])) { throw new MappingException("{$className} is missing the referencedBy attribute for the referrer field {$name}"); } if (!isset($attributes['referringDocument'])) { throw new MappingException("{$className} is missing the referringDocument attribute for the referrer field {$name}"); } $mapping = array('fieldName' => $name, 'referencedBy' => $attributes['referencedBy'], 'referringDocument' => $attributes['referringDocument'], 'cascade' => isset($attributes['cascade']) ? $this->getCascadeMode($attributes['cascade']) : 0); $class->mapReferrers($mapping); } } if (isset($element['versionName'])) { $class->mapVersionName(array('fieldName' => $element['versionName'])); } if (isset($element['versionCreated'])) { $class->mapVersionCreated(array('fieldName' => $element['versionCreated'])); } if (isset($element['lifecycleCallbacks'])) { foreach ($element['lifecycleCallbacks'] as $type => $methods) { foreach ($methods as $method) { $class->addLifecycleCallback($method, constant('Doctrine\\ODM\\PHPCR\\Event::' . $type)); } } } $class->validateClassMapping(); }
/** * {@inheritDoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ /* @var $xmlRoot SimpleXMLElement */ $xmlRoot = $this->getElement($className); if ($xmlRoot->getName() == 'entity') { if (isset($xmlRoot['repository-class'])) { $metadata->setCustomRepositoryClass((string) $xmlRoot['repository-class']); } if (isset($xmlRoot['read-only']) && $this->evaluateBoolean($xmlRoot['read-only'])) { $metadata->markReadOnly(); } } else { if ($xmlRoot->getName() == 'mapped-superclass') { $metadata->setCustomRepositoryClass(isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null); $metadata->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } // Evaluate <entity...> attributes $table = array(); if (isset($xmlRoot['table'])) { $table['name'] = (string) $xmlRoot['table']; } $metadata->setPrimaryTable($table); // Evaluate named queries if (isset($xmlRoot->{'named-queries'})) { foreach ($xmlRoot->{'named-queries'}->{'named-query'} as $namedQueryElement) { $metadata->addNamedQuery(array('name' => (string) $namedQueryElement['name'], 'query' => (string) $namedQueryElement['query'])); } } // Evaluate native named queries if (isset($xmlRoot->{'named-native-queries'})) { foreach ($xmlRoot->{'named-native-queries'}->{'named-native-query'} as $nativeQueryElement) { $metadata->addNamedNativeQuery(array('name' => isset($nativeQueryElement['name']) ? (string) $nativeQueryElement['name'] : null, 'query' => isset($nativeQueryElement->query) ? (string) $nativeQueryElement->query : null, 'resultClass' => isset($nativeQueryElement['result-class']) ? (string) $nativeQueryElement['result-class'] : null, 'resultSetMapping' => isset($nativeQueryElement['result-set-mapping']) ? (string) $nativeQueryElement['result-set-mapping'] : null)); } } // Evaluate sql result set mapping if (isset($xmlRoot->{'sql-result-set-mappings'})) { foreach ($xmlRoot->{'sql-result-set-mappings'}->{'sql-result-set-mapping'} as $rsmElement) { $entities = array(); $columns = array(); foreach ($rsmElement as $entityElement) { //<entity-result/> if (isset($entityElement['entity-class'])) { $entityResult = array('fields' => array(), 'entityClass' => (string) $entityElement['entity-class'], 'discriminatorColumn' => isset($entityElement['discriminator-column']) ? (string) $entityElement['discriminator-column'] : null); foreach ($entityElement as $fieldElement) { $entityResult['fields'][] = array('name' => isset($fieldElement['name']) ? (string) $fieldElement['name'] : null, 'column' => isset($fieldElement['column']) ? (string) $fieldElement['column'] : null); } $entities[] = $entityResult; } //<column-result/> if (isset($entityElement['name'])) { $columns[] = array('name' => (string) $entityElement['name']); } } $metadata->addSqlResultSetMapping(array('name' => (string) $rsmElement['name'], 'entities' => $entities, 'columns' => $columns)); } } /* not implemented specially anyway. use table = schema.table if (isset($xmlRoot['schema'])) { $metadata->table['schema'] = (string)$xmlRoot['schema']; }*/ if (isset($xmlRoot['inheritance-type'])) { $inheritanceType = (string) $xmlRoot['inheritance-type']; $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceType)); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate <discriminator-column...> if (isset($xmlRoot->{'discriminator-column'})) { $discrColumn = $xmlRoot->{'discriminator-column'}; $metadata->setDiscriminatorColumn(array('name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : null, 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : null, 'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null)); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate <discriminator-map...> if (isset($xmlRoot->{'discriminator-map'})) { $map = array(); foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) { $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class']; } $metadata->setDiscriminatorMap($map); } } } // Evaluate <change-tracking-policy...> if (isset($xmlRoot['change-tracking-policy'])) { $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . strtoupper((string) $xmlRoot['change-tracking-policy']))); } // Evaluate <indexes...> if (isset($xmlRoot->indexes)) { $metadata->table['indexes'] = array(); foreach ($xmlRoot->indexes->index as $index) { $columns = explode(',', (string) $index['columns']); if (isset($index['name'])) { $metadata->table['indexes'][(string) $index['name']] = array('columns' => $columns); } else { $metadata->table['indexes'][] = array('columns' => $columns); } } } // Evaluate <unique-constraints..> if (isset($xmlRoot->{'unique-constraints'})) { $metadata->table['uniqueConstraints'] = array(); foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $unique) { $columns = explode(',', (string) $unique['columns']); if (isset($unique['name'])) { $metadata->table['uniqueConstraints'][(string) $unique['name']] = array('columns' => $columns); } else { $metadata->table['uniqueConstraints'][] = array('columns' => $columns); } } } if (isset($xmlRoot->options)) { $metadata->table['options'] = $this->_parseOptions($xmlRoot->options->children()); } // The mapping assignement is done in 2 times as a bug might occurs on some php/xml lib versions // The internal SimpleXmlIterator get resetted, to this generate a duplicate field exception $mappings = array(); // Evaluate <field ...> mappings if (isset($xmlRoot->field)) { foreach ($xmlRoot->field as $fieldMapping) { $mapping = $this->columnToArray($fieldMapping); if (isset($mapping['version'])) { $metadata->setVersionMapping($mapping); unset($mapping['version']); } $metadata->mapField($mapping); } } foreach ($mappings as $mapping) { if (isset($mapping['version'])) { $metadata->setVersionMapping($mapping); } $metadata->mapField($mapping); } // Evaluate <id ...> mappings $associationIds = array(); foreach ($xmlRoot->id as $idElement) { if (isset($idElement['association-key']) && $this->evaluateBoolean($idElement['association-key'])) { $associationIds[(string) $idElement['name']] = true; continue; } $mapping = array('id' => true, 'fieldName' => (string) $idElement['name']); if (isset($idElement['type'])) { $mapping['type'] = (string) $idElement['type']; } if (isset($idElement['length'])) { $mapping['length'] = (string) $idElement['length']; } if (isset($idElement['column'])) { $mapping['columnName'] = (string) $idElement['column']; } if (isset($idElement['column-definition'])) { $mapping['columnDefinition'] = (string) $idElement['column-definition']; } $metadata->mapField($mapping); if (isset($idElement->generator)) { $strategy = isset($idElement->generator['strategy']) ? (string) $idElement->generator['strategy'] : 'AUTO'; $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $strategy)); } // Check for SequenceGenerator/TableGenerator definition if (isset($idElement->{'sequence-generator'})) { $seqGenerator = $idElement->{'sequence-generator'}; $metadata->setSequenceGeneratorDefinition(array('sequenceName' => (string) $seqGenerator['sequence-name'], 'allocationSize' => (string) $seqGenerator['allocation-size'], 'initialValue' => (string) $seqGenerator['initial-value'])); } else { if (isset($idElement->{'custom-id-generator'})) { $customGenerator = $idElement->{'custom-id-generator'}; $metadata->setCustomGeneratorDefinition(array('class' => (string) $customGenerator['class'])); } else { if (isset($idElement->{'table-generator'})) { throw MappingException::tableIdGeneratorNotImplemented($className); } } } } // Evaluate <one-to-one ...> mappings if (isset($xmlRoot->{'one-to-one'})) { foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) { $mapping = array('fieldName' => (string) $oneToOneElement['field'], 'targetEntity' => (string) $oneToOneElement['target-entity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($oneToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $oneToOneElement['fetch']); } if (isset($oneToOneElement['mapped-by'])) { $mapping['mappedBy'] = (string) $oneToOneElement['mapped-by']; } else { if (isset($oneToOneElement['inversed-by'])) { $mapping['inversedBy'] = (string) $oneToOneElement['inversed-by']; } $joinColumns = array(); if (isset($oneToOneElement->{'join-column'})) { $joinColumns[] = $this->joinColumnToArray($oneToOneElement->{'join-column'}); } else { if (isset($oneToOneElement->{'join-columns'})) { foreach ($oneToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; } if (isset($oneToOneElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($oneToOneElement->cascade); } if (isset($oneToOneElement['orphan-removal'])) { $mapping['orphanRemoval'] = $this->evaluateBoolean($oneToOneElement['orphan-removal']); } $metadata->mapOneToOne($mapping); } } // Evaluate <one-to-many ...> mappings if (isset($xmlRoot->{'one-to-many'})) { foreach ($xmlRoot->{'one-to-many'} as $oneToManyElement) { $mapping = array('fieldName' => (string) $oneToManyElement['field'], 'targetEntity' => (string) $oneToManyElement['target-entity'], 'mappedBy' => (string) $oneToManyElement['mapped-by']); if (isset($oneToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $oneToManyElement['fetch']); } if (isset($oneToManyElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($oneToManyElement->cascade); } if (isset($oneToManyElement['orphan-removal'])) { $mapping['orphanRemoval'] = $this->evaluateBoolean($oneToManyElement['orphan-removal']); } if (isset($oneToManyElement->{'order-by'})) { $orderBy = array(); foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; } $mapping['orderBy'] = $orderBy; } if (isset($oneToManyElement['index-by'])) { $mapping['indexBy'] = (string) $oneToManyElement['index-by']; } else { if (isset($oneToManyElement->{'index-by'})) { throw new \InvalidArgumentException("<index-by /> is not a valid tag"); } } $metadata->mapOneToMany($mapping); } } // Evaluate <many-to-one ...> mappings if (isset($xmlRoot->{'many-to-one'})) { foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) { $mapping = array('fieldName' => (string) $manyToOneElement['field'], 'targetEntity' => (string) $manyToOneElement['target-entity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($manyToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $manyToOneElement['fetch']); } if (isset($manyToOneElement['inversed-by'])) { $mapping['inversedBy'] = (string) $manyToOneElement['inversed-by']; } $joinColumns = array(); if (isset($manyToOneElement->{'join-column'})) { $joinColumns[] = $this->joinColumnToArray($manyToOneElement->{'join-column'}); } else { if (isset($manyToOneElement->{'join-columns'})) { foreach ($manyToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; if (isset($manyToOneElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($manyToOneElement->cascade); } $metadata->mapManyToOne($mapping); } } // Evaluate <many-to-many ...> mappings if (isset($xmlRoot->{'many-to-many'})) { foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) { $mapping = array('fieldName' => (string) $manyToManyElement['field'], 'targetEntity' => (string) $manyToManyElement['target-entity']); if (isset($manyToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $manyToManyElement['fetch']); } if (isset($manyToManyElement['orphan-removal'])) { $mapping['orphanRemoval'] = $this->evaluateBoolean($manyToManyElement['orphan-removal']); } if (isset($manyToManyElement['mapped-by'])) { $mapping['mappedBy'] = (string) $manyToManyElement['mapped-by']; } else { if (isset($manyToManyElement->{'join-table'})) { if (isset($manyToManyElement['inversed-by'])) { $mapping['inversedBy'] = (string) $manyToManyElement['inversed-by']; } $joinTableElement = $manyToManyElement->{'join-table'}; $joinTable = array('name' => (string) $joinTableElement['name']); if (isset($joinTableElement['schema'])) { $joinTable['schema'] = (string) $joinTableElement['schema']; } foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); } foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) { $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); } $mapping['joinTable'] = $joinTable; } } if (isset($manyToManyElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($manyToManyElement->cascade); } if (isset($manyToManyElement->{'order-by'})) { $orderBy = array(); foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; } $mapping['orderBy'] = $orderBy; } if (isset($manyToManyElement['index-by'])) { $mapping['indexBy'] = (string) $manyToManyElement['index-by']; } else { if (isset($manyToManyElement->{'index-by'})) { throw new \InvalidArgumentException("<index-by /> is not a valid tag"); } } $metadata->mapManyToMany($mapping); } } // Evaluate association-overrides if (isset($xmlRoot->{'attribute-overrides'})) { foreach ($xmlRoot->{'attribute-overrides'}->{'attribute-override'} as $overrideElement) { $fieldName = (string) $overrideElement['name']; foreach ($overrideElement->field as $field) { $mapping = $this->columnToArray($field); $mapping['fieldName'] = $fieldName; $metadata->setAttributeOverride($fieldName, $mapping); } } } // Evaluate association-overrides if (isset($xmlRoot->{'association-overrides'})) { foreach ($xmlRoot->{'association-overrides'}->{'association-override'} as $overrideElement) { $fieldName = (string) $overrideElement['name']; $override = array(); // Check for join-columns if (isset($overrideElement->{'join-columns'})) { $joinColumns = array(); foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } $override['joinColumns'] = $joinColumns; } // Check for join-table if ($overrideElement->{'join-table'}) { $joinTable = null; $joinTableElement = $overrideElement->{'join-table'}; $joinTable = array('name' => (string) $joinTableElement['name'], 'schema' => (string) $joinTableElement['schema']); if (isset($joinTableElement->{'join-columns'})) { foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement); } } if (isset($joinTableElement->{'inverse-join-columns'})) { foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) { $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement); } } $override['joinTable'] = $joinTable; } $metadata->setAssociationOverride($fieldName, $override); } } // Evaluate <lifecycle-callbacks...> if (isset($xmlRoot->{'lifecycle-callbacks'})) { foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) { $metadata->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\\ORM\\Events::' . (string) $lifecycleCallback['type'])); } } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $class) { /** @var $class \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */ try { $xmlRoot = $this->getElement($className); } catch (DoctrineMappingException $e) { // Convert Exception type for consistency with other drivers throw new MappingException($e->getMessage(), $e->getCode(), $e); } if (!$xmlRoot) { return; } if ($xmlRoot->getName() == 'document') { $class->setCustomRepositoryClass(isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null); if (isset($xmlRoot['indexed']) && $xmlRoot['indexed'] == true) { $class->indexed = true; } if (isset($xmlRoot['inheritance-root']) && $xmlRoot['inheritance-root']) { $class->markInheritanceRoot(); } } else { if ($xmlRoot->getName() == "embedded-document") { $class->isEmbeddedDocument = true; if (isset($xmlRoot['inheritance-root']) && $xmlRoot['inheritance-root']) { $class->markInheritanceRoot(); } } else { if ($xmlRoot->getName() == "mapped-superclass") { $class->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidDocument($className); } } } // Evaluate <field ...> mappings if (isset($xmlRoot->field)) { foreach ($xmlRoot->field as $fieldMapping) { $class->mapField(array('fieldName' => (string) $fieldMapping['name'], 'jsonName' => isset($fieldMapping['json-name']) ? (string) $fieldMapping['json-name'] : null, 'indexed' => isset($fieldMapping['index']) ? (bool) $fieldMapping['index'] : false, 'type' => isset($fieldMapping['type']) ? (string) $fieldMapping['type'] : null, 'isVersionField' => isset($fieldMapping['version']) ? true : null)); } } // Evaluate <id ..> mappings foreach ($xmlRoot->id as $idElement) { $class->mapField(array('fieldName' => (string) $idElement['name'], 'indexed' => isset($idElement['index']) ? (bool) $idElement['index'] : false, 'type' => isset($idElement['type']) ? (string) $idElement['type'] : null, 'id' => true, 'strategy' => isset($idElement['strategy']) ? (string) $idElement['strategy'] : null)); } // Evaluate <version ..> mappings foreach ($xmlRoot->version as $versionElement) { $class->mapField(array('fieldName' => (string) $versionElement['name'], 'type' => 'string', 'isVersionField' => true, 'jsonName' => '_rev')); } // Evaluate <many-to-one ..> mappings if (isset($xmlRoot->{"reference-one"})) { foreach ($xmlRoot->{"reference-one"} as $referenceOneElement) { $class->mapManyToOne(array('cascade' => isset($referenceOneElement->cascade) ? $this->getCascadeMode($referenceOneElement->cascade) : 0, 'targetDocument' => (string) $referenceOneElement['target-document'], 'fieldName' => (string) $referenceOneElement['field'], 'jsonName' => isset($referenceOneElement['json-name']) ? (string) $referenceOneElement['json-name'] : null, 'indexed' => isset($referenceOneElement['index']) ? (bool) $referenceOneElement['index'] : false)); } } // Evaluate <many-to-one ..> mappings if (isset($xmlRoot->{"reference-many"})) { foreach ($xmlRoot->{"reference-many"} as $referenceManyElement) { $class->mapManyToMany(array('cascade' => isset($referenceManyElement->cascade) ? $this->getCascadeMode($referenceManyElement->cascade) : 0, 'targetDocument' => (string) $referenceManyElement['target-document'], 'fieldName' => (string) $referenceManyElement['field'], 'jsonName' => isset($referenceManyElement['json-name']) ? (string) $referenceManyElement['json-name'] : null, 'mappedBy' => isset($referenceManyElement['mapped-by']) ? (string) $referenceManyElement['mapped-by'] : null)); } } // Evaluate <attachments ..> mapping if (isset($xmlRoot->{"attachments"})) { $class->mapAttachments((string) $xmlRoot->{"attachments"}[0]['field']); } // Evaluate <embed-one /> if (isset($xmlRoot->{'embed-one'})) { foreach ($xmlRoot->{'embed-one'} as $embedOneElement) { $class->mapEmbedded(array('targetDocument' => (string) $embedOneElement['target-document'], 'fieldName' => (string) $embedOneElement['field'], 'jsonName' => isset($embedOneElement['json-name']) ? (string) $embedOneElement['json-name'] : null, 'embedded' => 'one')); } } // Evaluate <embed-many /> if (isset($xmlRoot->{'embed-many'})) { foreach ($xmlRoot->{'embed-many'} as $embedManyElement) { $class->mapEmbedded(array('targetDocument' => (string) $embedManyElement['target-document'], 'fieldName' => (string) $embedManyElement['field'], 'jsonName' => isset($embedManyElement['json-name']) ? (string) $embedManyElement['json-name'] : null, 'embedded' => 'many')); } } }