/**
  * @param BundleInterface $bundle         The bundle
  * @param string          $entity         The entity name
  * @param string          $format         The format
  * @param array           $fields         The fields
  * @param boolean         $withRepository With repository
  * @param string          $prefix         A prefix
  *
  * @throws \RuntimeException
  */
 public function generate(BundleInterface $bundle, $entity, $format, array $fields, $withRepository, $prefix)
 {
     // configure the bundle (needed if the bundle does not contain any Entities yet)
     $config = $this->registry->getManager(null)->getConfiguration();
     $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces()));
     $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity;
     $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php';
     if (file_exists($entityPath)) {
         throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass));
     }
     $class = new ClassMetadataInfo($entityClass);
     if ($withRepository) {
         $entityClass = preg_replace('/\\\\Entity\\\\/', '\\Repository\\', $entityClass, 1);
         $class->customRepositoryClassName = $entityClass . 'Repository';
     }
     foreach ($fields as $field) {
         $class->mapField($field);
     }
     $class->setPrimaryTable(array('name' => $prefix . $this->getTableNameFromEntityName($entity)));
     $entityGenerator = $this->getEntityGenerator();
     $entityCode = $entityGenerator->generateEntityClass($class);
     $mappingPath = $mappingCode = false;
     $this->filesystem->mkdir(dirname($entityPath));
     file_put_contents($entityPath, $entityCode);
     if ($mappingPath) {
         $this->filesystem->mkdir(dirname($mappingPath));
         file_put_contents($mappingPath, $mappingCode);
     }
     if ($withRepository) {
         $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\'));
         $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path);
     }
     $this->addGeneratedEntityClassLoader($entityClass, $entityPath);
 }
 public function testAddedOptions()
 {
     $this->metadata->expects($this->once())->method('getTableName')->will($this->returnValue(IndexText::TABLE_NAME));
     $this->event->expects($this->once())->method('getClassMetadata')->will($this->returnValue($this->metadata));
     $this->listener->loadClassMetadata($this->event);
     $this->assertEquals(['options' => ['engine' => PdoMysql::ENGINE_MYISAM], 'indexes' => ['value' => ['columns' => ['value']]]], $this->metadata->table);
 }
Пример #3
0
 public static function validateField(ClassMetadataInfo $meta, $field)
 {
     $fieldMapping = $meta->getFieldMapping($field);
     if (!in_array($fieldMapping['type'], self::$validTypes)) {
         throw new InvalidMappingException(sprintf('Field "%s" must be of one of the following types: "%s"', $fieldMapping['type'], implode(', ', self::$validTypes)));
     }
 }
 /**
  * @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle\MySampleBundle")
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle'));
     $entity = str_replace('/', '\\', $input->getArgument('entity'));
     $fullEntityClassName = $bundle->getNamespace() . '\\Entity\\' . $entity;
     $mappingType = $input->getOption('mapping-type');
     $class = new ClassMetadataInfo($fullEntityClassName);
     $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     // Map the specified fields
     $fields = $input->getOption('fields');
     if ($fields) {
         $e = explode(' ', $fields);
         foreach ($e as $value) {
             $e = explode(':', $value);
             $name = $e[0];
             if (strlen($name)) {
                 $type = isset($e[1]) ? $e[1] : 'string';
                 preg_match_all('/(.*)\\((.*)\\)/', $type, $matches);
                 $type = isset($matches[1][0]) ? $matches[1][0] : $type;
                 $length = isset($matches[2][0]) ? $matches[2][0] : null;
                 $class->mapField(array('fieldName' => $name, 'type' => $type, 'length' => $length));
             }
         }
     }
     // Setup a new exporter for the mapping type specified
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($mappingType);
     $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php';
     if (file_exists($entityPath)) {
         throw new \RuntimeException(sprintf("Entity %s already exists.", $class->name));
     }
     if ('annotation' === $mappingType) {
         $exporter->setEntityGenerator($this->getEntityGenerator());
         $entityCode = $exporter->exportClassMetadata($class);
         $mappingPath = $mappingCode = false;
     } else {
         $mappingType = 'yaml' == $mappingType ? 'yml' : $mappingType;
         $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $fullEntityClassName) . '.orm.' . $mappingType;
         $mappingCode = $exporter->exportClassMetadata($class);
         $entityGenerator = $this->getEntityGenerator();
         $entityCode = $entityGenerator->generateEntityClass($class);
         if (file_exists($mappingPath)) {
             throw new \RuntimeException(sprintf("Cannot generate entity when mapping <info>%s</info> already exists", $mappingPath));
         }
     }
     $output->writeln(sprintf('Generating entity for "<info>%s</info>"', $bundle->getName()));
     $output->writeln(sprintf('  > entity <comment>%s</comment> into <info>%s</info>', $fullEntityClassName, $entityPath));
     if (!is_dir($dir = dirname($entityPath))) {
         mkdir($dir, 0777, true);
     }
     file_put_contents($entityPath, $entityCode);
     if ($mappingPath) {
         $output->writeln(sprintf('  > mapping into <info>%s</info>', $mappingPath));
         if (!is_dir($dir = dirname($mappingPath))) {
             mkdir($dir, 0777, true);
         }
         file_put_contents($mappingPath, $mappingCode);
     }
 }
 function let(PropertyTransformerInterface $transformer, ColumnInfoInterface $columnInfo, ClassMetadataInfo $metadata)
 {
     $this->beConstructedWith($transformer, 'array');
     $columnInfo->getPropertyPath()->willReturn('property_path');
     $metadata->hasField('property_path')->willReturn(true);
     $metadata->getTypeOfField('property_path')->willReturn('array');
 }
 /**
  * Unset the association mappings of a metadata.
  *
  * @param ClassMetadataInfo $metadata
  */
 protected function unsetAssociationMappings(ClassMetadataInfo $metadata)
 {
     foreach ($metadata->getAssociationMappings() as $key => $value) {
         if ($this->hasRelation($value['type'])) {
             unset($metadata->associationMappings[$key]);
         }
     }
 }
Пример #7
0
 public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata)
 {
     $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id'));
     $metadata->mapField(array('fieldName' => 'value', 'type' => 'float'));
     $metadata->isMappedSuperclass = true;
     $metadata->setCustomRepositoryClass("Doctrine\\Tests\\Models\\DDC869\\DDC869PaymentRepository");
     $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO);
 }
Пример #8
0
 public function testManyToManyHasPrefix()
 {
     $this->metadata->mapManyToMany(['fieldName' => 'fooBar', 'targetEntity' => 'bar']);
     $tablePrefix = new TablePrefixListener('someprefix_');
     $tablePrefix->loadClassMetadata($this->args);
     $this->assertEquals('someprefix_foo', $this->metadata->getTableName());
     $this->assertEquals('someprefix_foo_bar', $this->metadata->associationMappings['fooBar']['joinTable']['name']);
 }
 /**
  * Extends the mapping
  *
  * @param ClassMetadataInfo           $metadata
  * @param MappingDefinitionCollection $collection
  */
 private function extendClassMetadata(ClassMetadataInfo $metadata, MappingDefinitionCollection $collection)
 {
     $collection->forAll(function (MappingDefinitionInterface $definition) use($metadata) {
         $reflectionClass = $metadata->getReflectionClass();
         if (true === $reflectionClass->hasProperty($definition->getPropertyName())) {
             $metadata->{$definition->getClassMetadataMethod()}($definition->getOptions());
         }
     });
 }
 /**
  * {@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);
         }
     }
 }
 /**
  * @param ClassMetadataInfo $metadata
  *
  * @return string
  */
 public function getTableName(ClassMetadataInfo $metadata)
 {
     $tableName = $metadata->getTableName();
     //## Fix for doctrine/orm >= 2.5
     if (method_exists($metadata, 'getSchemaName') && $metadata->getSchemaName()) {
         $tableName = $metadata->getSchemaName() . '.' . $tableName;
     }
     return $this->getTablePrefix() . $tableName . $this->getTableSuffix();
 }
 /**
  * @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);
 }
 /**
  * Returns class annotations.
  *
  * @param ClassMetadataInfo $metadata
  *
  * @return array
  */
 protected function getClassAnnotations($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);
     }
     return $this->readAnnotations($class);
 }
Пример #14
0
 /**
  * {@inheritdoc}
  */
 public function loadMetadataForClass($className, \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata)
 {
     $element = $this->getElement($className, true);
     // Customizing for Cloudrexx: YamlEntity extension
     if ($element['type'] == 'YamlEntity') {
         $metadata->setCustomRepositoryClass(isset($element['repositoryClass']) ? $element['repositoryClass'] : null);
         $metadata->isMappedSuperclass = true;
     }
     parent::loadMetadataForClass($className, $metadata);
 }
 /**
  * @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle\MySampleBundle")
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!preg_match('/Bundle$/', $bundle = $input->getArgument('bundle'))) {
         throw new \InvalidArgumentException('The bundle name must end with Bundle. Example: "Bundle\\MySampleBundle".');
     }
     $dirs = $this->container->get('kernel')->getBundleDirs();
     $tmp = str_replace('\\', '/', $bundle);
     $namespace = str_replace('/', '\\', dirname($tmp));
     $bundle = basename($tmp);
     if (!isset($dirs[$namespace])) {
         throw new \InvalidArgumentException(sprintf('Unable to initialize the bundle entity (%s not defined).', $namespace));
     }
     $entity = $input->getArgument('entity');
     $entityNamespace = $namespace . '\\' . $bundle . '\\Entity';
     $fullEntityClassName = $entityNamespace . '\\' . $entity;
     $tmp = str_replace('\\', '/', $fullEntityClassName);
     $tmp = str_replace('/', '\\', dirname($tmp));
     $className = basename($tmp);
     $mappingType = $input->getOption('mapping-type');
     $mappingType = $mappingType ? $mappingType : 'xml';
     $class = new ClassMetadataInfo($fullEntityClassName);
     $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     // Map the specified fields
     $fields = $input->getOption('fields');
     if ($fields) {
         $e = explode(' ', $fields);
         foreach ($e as $value) {
             $e = explode(':', $value);
             $name = $e[0];
             $type = isset($e[1]) ? $e[1] : 'string';
             preg_match_all('/(.*)\\((.*)\\)/', $type, $matches);
             $type = isset($matches[1][0]) ? $matches[1][0] : $type;
             $length = isset($matches[2][0]) ? $matches[2][0] : null;
             $class->mapField(array('fieldName' => $name, 'type' => $type, 'length' => $length));
         }
     }
     // Setup a new exporter for the mapping type specified
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($mappingType);
     if ('annotation' === $mappingType) {
         $path = $dirs[$namespace] . '/' . $bundle . '/Entity/' . str_replace($entityNamespace . '\\', null, $fullEntityClassName) . '.php';
         $exporter->setEntityGenerator($this->getEntityGenerator());
     } else {
         $mappingType = 'yaml' == $mappingType ? 'yml' : $mappingType;
         $path = $dirs[$namespace] . '/' . $bundle . '/Resources/config/doctrine/metadata/orm/' . str_replace('\\', '.', $fullEntityClassName) . '.dcm.' . $mappingType;
     }
     $code = $exporter->exportClassMetadata($class);
     if (!is_dir($dir = dirname($path))) {
         mkdir($dir, 0777, true);
     }
     $output->writeln(sprintf('Generating entity for "<info>%s</info>"', $bundle));
     $output->writeln(sprintf('  > generating <comment>%s</comment>', $fullEntityClassName));
     file_put_contents($path, $code);
 }
 /**
  * @param ColumnInfoInterface  $columnInfo
  * @param ORMClassMetadataInfo $metadata
  *
  * @return array
  */
 private function getORMTransformerInfo(ColumnInfoInterface $columnInfo, ORMClassMetadataInfo $metadata)
 {
     if (!$metadata->hasAssociation($columnInfo->getPropertyPath())) {
         return;
     }
     $mapping = $metadata->getAssociationMapping($columnInfo->getPropertyPath());
     if (!$this->doctrine->getRepository($mapping['targetEntity']) instanceof ReferableEntityRepositoryInterface) {
         return;
     }
     return array($this->transformer, array('class' => $mapping['targetEntity'], 'multiple' => ORMClassMetadataInfo::MANY_TO_MANY === $mapping['type']));
 }
Пример #17
0
 /**
  * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata
  */
 public static function loadMetadata(ORM\ClassMetadataInfo $metadata)
 {
     $metadata->setTableName('album');
     $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE);
     $metadata->setCustomRepositoryClass('Orm\\Repository\\AlbumRepository');
     $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist');
     $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate');
     $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100));
     $metadata->mapField(array('id' => true, 'fieldName' => 'websiteid', 'type' => 'string', 'length' => 100));
     $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255));
     $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0));
 }
Пример #18
0
 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);
 }
 protected function setUp()
 {
     $this->classMetadata = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadataInfo')->disableOriginalConstructor()->setMethods(array('getSingleIdentifierFieldName'))->getMock();
     $this->classMetadata->expects($this->any())->method('getSingleIdentifierFieldName')->will($this->returnValue(self::TEST_IDENTIFIER));
     $this->ormConfiguration = $this->getMockBuilder('Doctrine\\ORM\\Configuration')->disableOriginalConstructor()->setMethods(array('addCustomHydrationMode'))->getMock();
     $this->entityManager = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->setMethods(array('getClassMetadata', 'getConfiguration'))->getMock();
     $this->entityManager->expects($this->any())->method('getClassMetadata')->with(self::TEST_CLASS)->will($this->returnValue($this->classMetadata));
     $this->entityManager->expects($this->any())->method('getConfiguration')->will($this->returnValue($this->ormConfiguration));
     $this->registry = $this->getMockBuilder('Doctrine\\Common\\Persistence\\ManagerRegistry')->disableOriginalConstructor()->setMethods('getManager', 'getRepository')->getMockForAbstractClass();
     $this->registry->expects($this->any())->method('getManager')->will($this->returnValue($this->entityManager));
     $this->registry->expects($this->any())->method('getRepository')->with(self::TEST_CLASS)->will($this->returnValue($this->getEntityRepository()));
     $this->type = new TranslatableEntityType($this->registry);
 }
 /**
  * Returns an array of fields. Fields can be both column fields and
  * association fields.
  *
  * @param  ClassMetadataInfo $metadata
  * @return array             $fields
  */
 private function getFieldsFromMetadata(ClassMetadataInfo $metadata)
 {
     $fields = (array) $metadata->fieldMappings;
     // Remove the primary key field if it's not managed manually
     if (!$metadata->isIdentifierNatural()) {
         foreach ($metadata->identifier as $id) {
             if (array_key_exists($id, $fields)) {
                 unset($fields[$id]);
             }
         }
     }
     return $fields;
 }
 /**
  * Returns an array of fields. Fields can be both column fields and
  * association fields.
  *
  * @param  ClassMetadataInfo $metadata
  * @return array             $fields
  */
 private function getFieldsFromMetadata(ClassMetadataInfo $metadata)
 {
     $fields = (array) $metadata->fieldNames;
     // Remove the primary key field if it's not managed manually
     if (!$metadata->isIdentifierNatural()) {
         $fields = array_diff($fields, $metadata->identifier);
     }
     foreach ($metadata->associationMappings as $fieldName => $relation) {
         if ($relation['type'] !== ClassMetadataInfo::ONE_TO_MANY) {
             $fields[] = $fieldName;
         }
     }
     return $fields;
 }
 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);
 }
Пример #23
0
 /**
  * Creates an entity.
  *
  * @static
  */
 public static function create($name, $path, array $fields, $annotationPrefix = 'ORM\\')
 {
     self::$annotationPrefix = $annotationPrefix;
     self::$name = $name;
     self::$path = $path;
     self::$fields = $fields;
     $class = new ClassMetadataInfo(self::$name);
     $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     foreach (self::$fields as $field) {
         $class->mapField($field);
     }
     file_put_contents(self::$path, self::getEntityGenerator()->generateEntityClass($class));
 }
 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);
 }
Пример #25
0
 public function generate(BundleInterface $bundle, $entity, $format, array $fields, $withRepository)
 {
     // configure the bundle (needed if the bundle does not contain any Entities yet)
     $config = $this->registry->getManager(null)->getConfiguration();
     $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces()));
     $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity;
     $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php';
     if (file_exists($entityPath)) {
         throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass));
     }
     $class = new ClassMetadataInfo($entityClass);
     $namingArray = Helper\NamingHelper::getNamingArray($bundle);
     $class->table['name'] = $namingArray['vendor'] . '__' . $namingArray['bundle'] . '__' . strtolower($entity);
     if ($withRepository) {
         $class->customRepositoryClassName = $entityClass . 'Repository';
     }
     $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     foreach ($fields as $field) {
         $class->mapField($field);
     }
     $entityGenerator = $this->getEntityGenerator();
     if ('annotation' === $format) {
         $entityGenerator->setGenerateAnnotations(true);
         $entityCode = $entityGenerator->generateEntityClass($class);
         $mappingPath = $mappingCode = false;
     } else {
         $cme = new ClassMetadataExporter();
         $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format);
         $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $entity) . '.orm.' . $format;
         if (file_exists($mappingPath)) {
             throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath));
         }
         $mappingCode = $exporter->exportClassMetadata($class);
         $entityGenerator->setGenerateAnnotations(false);
         $entityCode = $entityGenerator->generateEntityClass($class);
     }
     $this->filesystem->mkdir(dirname($entityPath));
     file_put_contents($entityPath, $entityCode);
     if ($mappingPath) {
         $this->filesystem->mkdir(dirname($mappingPath));
         file_put_contents($mappingPath, $mappingCode);
     }
     if ($withRepository) {
         $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\'));
         $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path);
     }
 }
Пример #26
0
 /**
  * Adds Field.
  *
  * @param string $name
  * @param string $type
  * @param array  $mapping
  *
  * @return ClassMetadataBuilder
  */
 public function addField($name, $type, array $mapping = array())
 {
     $mapping['fieldName'] = $name;
     $mapping['type'] = $type;
     $this->cm->mapField($mapping);
     return $this;
 }
Пример #27
0
 /**
  * Returns an array of fields. Fields can be both column fields and
  * association fields.
  *
  * @param ClassMetadataInfo $metadata
  *
  * @return array $fields
  */
 private function getFieldsFromMetadata(ClassMetadataInfo $metadata)
 {
     $fields = (array) $metadata->fieldNames;
     if (!$metadata->isIdentifierNatural()) {
         $fields = array_diff($fields, $metadata->identifier);
     }
     $fieldsMapping = array();
     foreach ($fields as $field) {
         $fieldsMapping[$field] = $metadata->getTypeOfField($field);
     }
     foreach ($metadata->associationMappings as $fieldName => $relation) {
         if ($relation['type'] !== ClassMetadataInfo::ONE_TO_MANY) {
             $fieldsMapping[$fieldName] = 'relation';
         }
     }
     return $fieldsMapping;
 }
Пример #28
0
 /**
  * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata
  */
 public static function loadMetadata(ORM\ClassMetadataInfo $metadata)
 {
     $metadata->setTableName('user_opt_in');
     $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE);
     $metadata->setCustomRepositoryClass('Orm\\Repository\\OptInRepository');
     $metadata->mapField(array('id' => true, 'fieldName' => 'userid', 'type' => 'string', 'length' => 100));
     $metadata->mapField(array('id' => true, 'unique' => true, 'fieldName' => 'code', 'type' => 'string', 'length' => 100));
     $metadata->mapField(array('fieldName' => 'timestamp', 'type' => 'datetime'));
     $metadata->mapField(array('fieldName' => 'mode', 'type' => 'string', 'length' => 100));
 }
 public function generateBookEntityFixture()
 {
     $metadata = new ClassMetadataInfo($this->_namespace . '\\EntityGeneratorBook');
     $metadata->namespace = $this->_namespace;
     $metadata->customRepositoryClassName = $this->_namespace . '\\EntityGeneratorBookRepository';
     $metadata->table['name'] = 'book';
     $metadata->mapField(array('fieldName' => 'name', 'type' => 'string'));
     $metadata->mapField(array('fieldName' => 'status', 'type' => 'string', 'default' => 'published'));
     $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $metadata->mapOneToOne(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\EntityGeneratorAuthor', 'mappedBy' => 'book'));
     $joinColumns = array(array('name' => 'author_id', 'referencedColumnName' => 'id'));
     $metadata->mapManyToMany(array('fieldName' => 'comments', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\EntityGeneratorComment', 'joinTable' => array('name' => 'book_comment', 'joinColumns' => array(array('name' => 'book_id', 'referencedColumnName' => 'id')), 'inverseJoinColumns' => array(array('name' => 'comment_id', 'referencedColumnName' => 'id')))));
     $metadata->addLifecycleCallback('loading', 'postLoad');
     $metadata->addLifecycleCallback('willBeRemoved', 'preRemove');
     $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     $this->_generator->writeEntityClass($metadata, $this->_tmpDir);
     return $metadata;
 }
Пример #30
0
 /**
  * Get default order by.
  *
  * @return array|null
  */
 protected function getDefaultOrderBy()
 {
     $ids = $this->metadata->getIdentifierFieldNames();
     $orderBy = $ids ? [] : null;
     foreach ($ids as $pk) {
         $orderBy[$pk] = 'ASC';
     }
     return $orderBy;
 }