/** * @param ClassMetadataInfo $metadata * @param string $outputDir * @param Closure $collectionNameBuilder */ public function generate(ClassMetadataInfo $metadata, $outputDir, Closure $collectionNameBuilder) { $tpl = file_get_contents(CodeGeneratorHelper::absPath(EntityCollectionTemplate::class, RootPath::path())); $tplNs = CodeGeneratorHelper::ns(EntityCollectionTemplate::class); $tplSimpleName = CodeGeneratorHelper::simpleName(EntityCollectionTemplate::class); $entityFqcn = CodeGeneratorHelper::simpleName(EntityFqcn::class); $collectionClassName = $collectionNameBuilder($metadata->getName()); $code = CodeGeneratorHelper::render($tpl, array($tplNs => CodeGeneratorHelper::ns($collectionClassName), $tplSimpleName => CodeGeneratorHelper::simpleName($collectionClassName), $entityFqcn => CodeGeneratorHelper::fqn($metadata->getName()))); CodeGeneratorHelper::save($collectionClassName, $code, $outputDir); }
protected function generateCodeBody(ClassMetadataInfo $metadata) { $methods = array(); $methods[] = $this->generateFindBy($metadata->getName()); foreach ($metadata->fieldMappings as $fieldMapping) { $methods[] = $this->generateFieldFindBy($metadata->getName(), $fieldMapping['type'], $fieldMapping['fieldName']); } foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { $methods[] = $this->generateFieldFindBy($metadata->getName(), $embeddedClass['class'], $fieldName); } foreach ($metadata->associationMappings as $associationMapping) { $methods[] = $this->generateFieldFindBy($metadata->getName(), $associationMapping['targetEntity'], $associationMapping['fieldName']); } return implode("\n", $methods); }
/** * {@inheritdoc} */ public function traverse(ClassMetadataInfo $metadata) { $class = $metadata->getName(); if (true === $this->collection->has($class)) { foreach ($this->collection->get($class) as $enhancer) { $enhancer->visitClassMetadata($metadata); } } }
public function testLoadMetadataForClass() { $metadata = new ClassMetadataInfo('Giftcards\\Encryption\\Tests\\Doctrine\\MockEntityWithEncryptedProperties'); $metadata->reflClass = new \ReflectionClass($metadata->getName()); $this->driver->loadMetadataForClass($metadata->getName(), $metadata); $this->assertTrue($metadata->hasEncryptedProperties); $this->assertEquals(array('encryptedProperty' => array('profile' => null)), $metadata->encryptedProperties); $metadata = new ClassMetadataInfo('Giftcards\\Encryption\\Tests\\Doctrine\\MockEntityWithEncryptedPropertiesAndProfileSet'); $metadata->reflClass = new \ReflectionClass($metadata->getName()); $this->driver->loadMetadataForClass($metadata->getName(), $metadata); $this->assertTrue($metadata->hasEncryptedProperties); $this->assertEquals(array('encryptedProperty' => array('profile' => 'foo')), $metadata->encryptedProperties); }
/** * {@inheritdoc} */ protected function hasAssociationConfigs(ClassMetadataInfo $metadata, $associationName) { if ($this->isExtendField($metadata->getName(), $associationName)) { return false; } // check for default field of oneToMany or manyToMany relation if (strpos($associationName, ExtendConfigDumper::DEFAULT_PREFIX) === 0) { $guessedName = substr($associationName, strlen(ExtendConfigDumper::DEFAULT_PREFIX)); if (!empty($guessedName) && $this->isExtendField($metadata->getName(), $guessedName)) { return false; } } // check for inverse side field of oneToMany relation $targetClass = $metadata->getAssociationTargetClass($associationName); $prefix = strtolower(ExtendHelper::getShortClassName($targetClass)) . '_'; if (strpos($associationName, $prefix) === 0) { $guessedName = substr($associationName, strlen($prefix)); if (!empty($guessedName) && $this->isExtendField($targetClass, $guessedName)) { return false; } } return parent::hasAssociationConfigs($metadata, $associationName); }
function it_configures_the_mappings_of_a_model_that_overrides_an_original_model($configuration, ClassMetadataInfo $metadataInfo, MappingDriver $mappingDriver) { $originalQux1 = __NAMESPACE__ . '\\OriginalQux1'; $originalQux2 = __NAMESPACE__ . '\\OriginalQux2'; $overrideQux1 = __NAMESPACE__ . '\\OverrideQux1'; $overrideQux2 = __NAMESPACE__ . '\\OverrideQux2'; $mappingDriver->getAllClassNames()->willReturn([$originalQux1]); $configuration->getMetadataDriverImpl()->willReturn($mappingDriver); $configuration->getNamingStrategy()->willReturn(null); $metadataInfo->getName()->willReturn($overrideQux1); $mappingDriver->loadMetadataForClass($originalQux1, Argument::any())->shouldBeCalled(); $overrides = [['original' => $originalQux1, 'override' => $overrideQux1], ['original' => $originalQux2, 'override' => $overrideQux2]]; $this->configure($metadataInfo, $overrides, $configuration); }
/** * Set the association mappings of a metadata. * * @param ClassMetadataInfo $metadata * @param Configuration $configuration */ protected function setAssociationMappings(ClassMetadataInfo $metadata, Configuration $configuration) { $supportedClasses = $configuration->getMetadataDriverImpl()->getAllClassNames(); foreach (class_parents($metadata->getName()) as $parent) { if (in_array($parent, $supportedClasses)) { $parentMetadata = new OrmClassMetadata($parent, $configuration->getNamingStrategy()); $configuration->getMetadataDriverImpl()->loadMetadataForClass($parent, $parentMetadata); foreach ($parentMetadata->getAssociationMappings() as $key => $value) { if ($this->hasRelation($value['type'])) { $metadata->associationMappings[$key] = $value; } } } } }
/** * @param ClassMetadataInfo $metadata * @param $configuration */ private function setAssociationMappings(ClassMetadataInfo $metadata, $configuration) { foreach (class_parents($metadata->getName()) as $parent) { $parentMetadata = new ClassMetadata($parent, $configuration->getNamingStrategy()); if (in_array($parent, $configuration->getMetadataDriverImpl()->getAllClassNames())) { $configuration->getMetadataDriverImpl()->loadMetadataForClass($parent, $parentMetadata); if ($parentMetadata->isMappedSuperclass) { foreach ($parentMetadata->getAssociationMappings() as $key => $value) { if ($this->hasRelation($value['type'])) { $metadata->associationMappings[$key] = $value; } } } } } }
/** * @param ClassMetadataInfo $metadata * @param $configuration */ private function setAssociationMappings(ClassMetadataInfo $metadata, $configuration) { foreach (class_parents($metadata->getName()) as $parent) { if (false === in_array($parent, $configuration->getMetadataDriverImpl()->getAllClassNames())) { continue; } $parentMetadata = new ClassMetadata($parent, $configuration->getNamingStrategy()); // Wakeup Reflection $parentMetadata->wakeupReflection($this->getReflectionService()); // Load Metadata $configuration->getMetadataDriverImpl()->loadMetadataForClass($parent, $parentMetadata); if (false === $this->isResource($parentMetadata)) { continue; } if ($parentMetadata->isMappedSuperclass) { foreach ($parentMetadata->getAssociationMappings() as $key => $value) { if ($this->hasRelation($value['type'])) { $metadata->associationMappings[$key] = $value; } } } } }
/** * @param ClassMetadataInfo $metadata * @param Configuration $configuration */ private function setAssociationMappings(ClassMetadataInfo $metadata, Configuration $configuration) { if (!class_exists($metadata->getName())) { return; } foreach (class_parents($metadata->getName()) as $parent) { $parentMetadata = new ClassMetadata($parent, $configuration->getNamingStrategy()); if (!in_array($parent, $this->getAllClassNames($configuration))) { continue; } $configuration->getMetadataDriverImpl()->loadMetadataForClass($parent, $parentMetadata); if (!$parentMetadata->isMappedSuperclass) { continue; } // map relations foreach ($parentMetadata->getAssociationMappings() as $key => $value) { if ($this->hasRelation($value['type'])) { $value['sourceEntity'] = $metadata->getName(); $metadata->associationMappings[$key] = $value; } } } }
public static function getPrimaryKeyName(ClassMetadataInfo $metadata) { $fieldMappings = $metadata->fieldMappings; foreach ($fieldMappings as $mapping) { if (array_key_exists('id', $mapping) && $mapping['id']) { return $mapping['fieldName']; } } throw new \Exception(sprintf('Primary key not defined for %s', $metadata->getName())); }
/** * @param ClassMetadataInfo $metadata * @return bool */ protected function hasEntityConfigs(ClassMetadataInfo $metadata) { $classMetadata = $this->configManager->getEntityMetadata($metadata->getName()); return $classMetadata && $classMetadata->configurable; }
public function getBaseQueryCollectionClassName(ClassMetadataInfo $metadata) { return $this->getQueryCollectionClassNameByEntityClass($metadata->getName()); }
/** * Sets the type of the entity this manager is responsible for * * @param string $entityClass The FQCN of an entity */ public function setClass($entityClass) { $this->metadata = $this->om->getClassMetadata($entityClass); $this->class = $this->metadata->getName(); }
/** * @param ClassMetadataInfo $classMetadataInfo * @param string $dumpDirectory * * return void */ private function dumpFile(ClassMetadataInfo $classMetadataInfo, $dumpDirectory) { $this->output->writeln("[" . date('c') . "] dumping {$classMetadataInfo->getName()} ..."); $this->dumper->setClassMetadataInfo($classMetadataInfo); $file = $this->dumper->dumpToYaml($dumpDirectory); $this->output->writeln("[" . date('c') . "] successfully dumped in file {$file}"); $this->output->writeln(PHP_EOL); }
/** * @param $entity * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $classMetadataInfo * * @return string */ private function getIdentifierForEntity($entity, ClassMetadataInfo $classMetadataInfo) { $entityName = $classMetadataInfo->getName(); $fixtureEntityIdentifier = strtolower(str_replace('\\', '_', $entityName)); $identifiers = $classMetadataInfo->getIdentifier(); foreach ($identifiers as $identifier) { $fixtureEntityIdentifier .= '_' . $classMetadataInfo->getFieldValue($entity, $identifier); } return $fixtureEntityIdentifier; }
protected function generateQueryCollectionCondClass($metadatas, ClassMetadataInfo $metadata) { $code = file_get_contents(CodeGeneratorHelper::absPath(____QueryCondSimpleClassName____::class, RootPath::path())); $code = CodeGeneratorHelper::render($code, [__NAMESPACE__ => $metadata->getName()]); $code = CodeGeneratorHelper::render($code, ['/* <code> */' => $this->generateCondCodeBody($metadatas, $metadata)]); $code = CodeGeneratorHelper::render($code, array('QueryCondSimpleClassName' => CodeGeneratorHelper::simpleName($this->helper->getQueryCollectionCondClassNameByEntityClass($metadata->getName())), 'TableName' => $metadata->getTableName()), self::KEY_TEMPLATE); return $code; }
/** * @param ClassMetadataInfo $metadata * @param string $cacheDir * @param EntityGenerator $entityGenerator * @param OutputInterface $output */ public static function generateEntity(ClassMetadataInfo $metadata, $cacheDir = null, EntityGenerator $entityGenerator = null, OutputInterface $output = null) { global $container; if (!$cacheDir) { $cacheDir = $container['doctrine.orm.entitiesCacheDir']; } if (!$entityGenerator) { $entityGenerator = $container['doctrine.orm.entityGeneratorFactory']($GLOBALS['TL_CONFIG']['debugMode'] || $GLOBALS['TL_CONFIG']['doctrineDevMode']); } if ($output) { $output->write(sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL); } $entityGenerator->setClassToExtend(false); $classPath = explode('\\', $metadata->getName()); while (count($classPath)) { $className = implode('\\', $classPath); if (isset($GLOBALS['DOCTRINE_ENTITY_CLASS'][$className])) { $entityGenerator->setClassToExtend($GLOBALS['DOCTRINE_ENTITY_CLASS'][$className]); break; } array_pop($classPath); } $entityGenerator->writeEntityClass($metadata, $cacheDir); // force load the new generated class if (!class_exists($metadata->getName(), false)) { $path = $cacheDir . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->name) . '.php'; include $path; } }
/** * @param ClassMetadataInfo $metadata */ protected function loadUniques($eventArgs, ClassMetadataInfo $metadata) { if (!array_key_exists($metadata->getName(), $this->uniques)) { return; } foreach ($this->uniques[$metadata->getName()] as $name => $columns) { $metadata->table['uniqueConstraints'][$name] = array('columns' => $columns); } }
protected function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata) { $lines = array(); $lines[] = $this->spaces . '/**'; if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { /* **** MODIFICATION BEGIN **** */ $lines[] = $this->spaces . ' * @var ' . $this->getCollectionTypeName($metadata->getName()); /* **** MODIFICATION END **** */ } else { $lines[] = $this->spaces . ' * @var \\' . ltrim($associationMapping['targetEntity'], '\\'); } if ($this->generateAnnotations) { $lines[] = $this->spaces . ' *'; if (isset($associationMapping['id']) && $associationMapping['id']) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id'; if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; } } $type = null; switch ($associationMapping['type']) { case ClassMetadataInfo::ONE_TO_ONE: $type = 'OneToOne'; break; case ClassMetadataInfo::MANY_TO_ONE: $type = 'ManyToOne'; break; case ClassMetadataInfo::ONE_TO_MANY: $type = 'OneToMany'; break; case ClassMetadataInfo::MANY_TO_MANY: $type = 'ManyToMany'; break; } $typeOptions = array(); if (isset($associationMapping['targetEntity'])) { $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"'; } if (isset($associationMapping['inversedBy'])) { $typeOptions[] = 'inversedBy="' . $associationMapping['inversedBy'] . '"'; } if (isset($associationMapping['mappedBy'])) { $typeOptions[] = 'mappedBy="' . $associationMapping['mappedBy'] . '"'; } if ($associationMapping['cascade']) { $cascades = array(); if ($associationMapping['isCascadePersist']) { $cascades[] = '"persist"'; } if ($associationMapping['isCascadeRemove']) { $cascades[] = '"remove"'; } if ($associationMapping['isCascadeDetach']) { $cascades[] = '"detach"'; } if ($associationMapping['isCascadeMerge']) { $cascades[] = '"merge"'; } if ($associationMapping['isCascadeRefresh']) { $cascades[] = '"refresh"'; } if (count($cascades) === 5) { $cascades = array('"all"'); } $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}'; } if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval']) { $typeOptions[] = 'orphanRemoval=' . ($associationMapping['orphanRemoval'] ? 'true' : 'false'); } if (isset($associationMapping['fetch']) && $associationMapping['fetch'] !== ClassMetadataInfo::FETCH_LAZY) { $fetchMap = array(ClassMetadataInfo::FETCH_EXTRA_LAZY => 'EXTRA_LAZY', ClassMetadataInfo::FETCH_EAGER => 'EAGER'); $typeOptions[] = 'fetch="' . $fetchMap[$associationMapping['fetch']] . '"'; } $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . '' . $type . '(' . implode(', ', $typeOptions) . ')'; if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinColumns({'; $joinColumnsLines = array(); foreach ($associationMapping['joinColumns'] as $joinColumn) { if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) { $joinColumnsLines[] = $this->spaces . ' * ' . $joinColumnAnnot; } } $lines[] = implode(",\n", $joinColumnsLines); $lines[] = $this->spaces . ' * })'; } if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) { $joinTable = array(); $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"'; if (isset($associationMapping['joinTable']['schema'])) { $joinTable[] = 'schema="' . $associationMapping['joinTable']['schema'] . '"'; } $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ','; $lines[] = $this->spaces . ' * joinColumns={'; $joinColumnsLines = array(); foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) { $joinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); } $lines[] = implode("," . PHP_EOL, $joinColumnsLines); $lines[] = $this->spaces . ' * },'; $lines[] = $this->spaces . ' * inverseJoinColumns={'; $inverseJoinColumnsLines = array(); foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) { $inverseJoinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); } $lines[] = implode("," . PHP_EOL, $inverseJoinColumnsLines); $lines[] = $this->spaces . ' * }'; $lines[] = $this->spaces . ' * )'; } if (isset($associationMapping['orderBy'])) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'OrderBy({'; foreach ($associationMapping['orderBy'] as $name => $direction) { $lines[] = $this->spaces . ' * "' . $name . '"="' . $direction . '",'; } $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1); $lines[] = $this->spaces . ' * })'; } } $lines[] = $this->spaces . ' */'; return implode("\n", $lines); }
protected function unsetFieldMappings(ClassMetadataInfo $metadata, $wasMappedSuperclass) { // if class is overridden and class is not the interface itself ... // (class is "in between" in a multi level inheritance) if ($this->classIsOverridden($metadata->getName()) && !isset($this->overriddenEntities[$metadata->getName()])) { // ... unset all mapped fields (otherwise a MappingException "Duplicate definition of column" will be thrown // when loading the metadata of the actually used class) // it will later be added as mapping for the actually used class in setFieldMappings() foreach ($metadata->fieldMappings as $name => $mapping) { if (!isset($mapping['declared']) || $mapping['declared'] === $metadata->getName()) { unset($metadata->fieldMappings[$mapping['fieldName']]); unset($metadata->columnNames[$mapping['fieldName']]); unset($metadata->fieldNames[$mapping['columnName']]); } } } else { if ($this->classIsOverridden($metadata->getName()) && !$wasMappedSuperclass) { // ... set fields to declared / inherited to avoid MappingException "Duplicate definition of column" when // loading the metadata of sub classes (this only happens if this class originally was defined as entity but // changed to a mapped superclass by this listener - it is actually a "hack" to fix it like that but we did // not find a better way to get this working) // to make this work correctly, these fields will later be re-added in setFieldMappings() to the actual // class (but we will keep the declared / inherited flags this time) foreach ($metadata->fieldMappings as $name => $mapping) { if (!isset($mapping['declared'])) { // only if not already set if (!$metadata->getReflectionClass()->getProperty($name)->isPrivate()) { $metadata->fieldMappings[$mapping['fieldName']]['declared'] = $metadata->getName(); $metadata->fieldMappings[$mapping['fieldName']]['inherited'] = $metadata->getName(); } } } } } return; }
protected function generateEntityNamespace(ClassMetadataInfo $metadata) { return 'namespace ' . $metadata->getName() . ';'; }