protected function execute(InputInterface $input, OutputInterface $output)
 {
     $bundleClass = null;
     $bundleDirs = $this->container->get('kernel')->getBundleDirs();
     foreach ($this->container->get('kernel')->getBundles() as $bundle) {
         if (strpos(get_class($bundle), $input->getArgument('bundle')) !== false) {
             $tmp = dirname(str_replace('\\', '/', get_class($bundle)));
             $namespace = str_replace('/', '\\', dirname($tmp));
             $class = basename($tmp);
             if (isset($bundleDirs[$namespace])) {
                 $destPath = realpath($bundleDirs[$namespace]) . '/' . $class;
                 $bundleClass = $class;
                 break;
             }
         }
     }
     $type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
     if ('annotation' === $type) {
         $destPath .= '/Entity';
     } else {
         $destPath .= '/Resources/config/doctrine/metadata/orm';
     }
     if ('yaml' === $type) {
         $type = 'yml';
     }
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type);
     if ('annotation' === $type) {
         $entityGenerator = $this->getEntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     $emName = $input->getOption('em') ? $input->getOption('em') : 'default';
     $emServiceName = sprintf('doctrine.orm.%s_entity_manager', $emName);
     $em = $this->container->get($emServiceName);
     $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
     $em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     if ($metadata) {
         $output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', $emName));
         foreach ($metadata as $class) {
             $className = $class->name;
             $class->name = $namespace . '\\' . $bundleClass . '\\Entity\\' . $className;
             if ('annotation' === $type) {
                 $path = $destPath . '/' . $className . '.php';
             } else {
                 $path = $destPath . '/' . str_replace('\\', '.', $class->name) . '.dcm.' . $type;
             }
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
             $code = $exporter->exportClassMetadata($class);
             if (!is_dir($dir = dirname($path))) {
                 mkdir($dir, 0777, true);
             }
             file_put_contents($path, $code);
         }
     } else {
         $output->writeln('Database does not have any mapping information.' . PHP_EOL, 'ERROR');
     }
 }
 /**
  * @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);
     }
 }
 public function testTest()
 {
     $cme = new ClassMetadataExporter();
     $converter = new ConvertDoctrine1Schema(__DIR__ . '/doctrine1schema');
     $exporter = $cme->getExporter('yml', __DIR__ . '/convert');
     $exporter->setMetadatas($converter->getMetadatas());
     $exporter->export();
     $this->assertTrue(file_exists(__DIR__ . '/convert/User.dcm.yml'));
     $this->assertTrue(file_exists(__DIR__ . '/convert/Profile.dcm.yml'));
     $cme->addMappingSource(__DIR__ . '/convert');
     $metadatas = $cme->getMetadatas();
     $this->assertEquals(2, count($metadatas));
     $this->assertEquals('Profile', $metadatas['Profile']->name);
     $this->assertEquals('User', $metadatas['User']->name);
     $this->assertEquals(4, count($metadatas['Profile']->fieldMappings));
     $this->assertEquals(5, count($metadatas['User']->fieldMappings));
     $this->assertEquals('text', $metadatas['User']->fieldMappings['clob']['type']);
     $this->assertEquals('test_alias', $metadatas['User']->fieldMappings['theAlias']['columnName']);
     $this->assertEquals('theAlias', $metadatas['User']->fieldMappings['theAlias']['fieldName']);
     $this->assertEquals('Profile', $metadatas['Profile']->associationMappings['User']->sourceEntityName);
     $this->assertEquals('User', $metadatas['Profile']->associationMappings['User']->targetEntityName);
     $this->assertEquals('username', $metadatas['User']->primaryTable['uniqueConstraints']['username']['columns'][0]);
     unlink(__DIR__ . '/convert/User.dcm.yml');
     unlink(__DIR__ . '/convert/Profile.dcm.yml');
     rmdir(__DIR__ . '/convert');
 }
Example #4
0
 public function run()
 {
     $arguments = $this->getArguments();
     $cme = new ClassMetadataExporter();
     $cme->setEntityManager($this->getConfiguration()->getAttribute('em'));
     $printer = $this->getPrinter();
     // Get exporter and configure it
     $exporter = $cme->getExporter($arguments['to'], $arguments['dest']);
     if ($arguments['to'] === 'annotation') {
         $entityGenerator = new EntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
         if (isset($arguments['extend']) && $arguments['extend']) {
             $entityGenerator->setClassToExtend($arguments['extend']);
         }
         if (isset($arguments['num-spaces']) && $arguments['extend']) {
             $entityGenerator->setNumSpaces($arguments['num-spaces']);
         }
     }
     $from = (array) $arguments['from'];
     foreach ($from as $source) {
         $cme->addMappingSource($source);
     }
     $metadatas = $cme->getMetadatas();
     foreach ($metadatas as $metadata) {
         $printer->writeln(sprintf('Processing entity "%s"', $printer->format($metadata->name, 'KEYWORD')));
     }
     $printer->writeln('');
     $printer->writeln(sprintf('Exporting "%s" mapping information to "%s"', $printer->format($arguments['to'], 'KEYWORD'), $printer->format($arguments['dest'], 'KEYWORD')));
     $exporter->setMetadatas($metadatas);
     $exporter->export();
 }
 public function testTest()
 {
     if (!class_exists('Symfony\\Component\\Yaml\\Yaml', true)) {
         $this->markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.');
     }
     $cme = new ClassMetadataExporter();
     $converter = new ConvertDoctrine1Schema(__DIR__ . '/doctrine1schema');
     $exporter = $cme->getExporter('yml', __DIR__ . '/convert');
     $exporter->setOverwriteExistingFiles(true);
     $exporter->setMetadata($converter->getMetadata());
     $exporter->export();
     $this->assertTrue(file_exists(__DIR__ . '/convert/User.dcm.yml'));
     $this->assertTrue(file_exists(__DIR__ . '/convert/Profile.dcm.yml'));
     $metadataDriver = new \Doctrine\ORM\Mapping\Driver\YamlDriver(__DIR__ . '/convert');
     $em = $this->_createEntityManager($metadataDriver);
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     $profileClass = $cmf->getMetadataFor('Profile');
     $userClass = $cmf->getMetadataFor('User');
     $this->assertEquals(2, count($metadata));
     $this->assertEquals('Profile', $profileClass->name);
     $this->assertEquals('User', $userClass->name);
     $this->assertEquals(4, count($profileClass->fieldMappings));
     $this->assertEquals(5, count($userClass->fieldMappings));
     $this->assertEquals('text', $userClass->fieldMappings['clob']['type']);
     $this->assertEquals('test_alias', $userClass->fieldMappings['theAlias']['columnName']);
     $this->assertEquals('theAlias', $userClass->fieldMappings['theAlias']['fieldName']);
     $this->assertEquals('Profile', $profileClass->associationMappings['User']['sourceEntity']);
     $this->assertEquals('User', $profileClass->associationMappings['User']['targetEntity']);
     $this->assertEquals('username', $userClass->table['uniqueConstraints']['username']['columns'][0]);
 }
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $factory = $this->getContainer()->get('doctrine')->getManager($input->getArgument('manager'))->getMetadataFactory();
     $metadata = $factory->getMetadataFor($input->getArgument('model'));
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter('php');
     $output->writeln($exporter->exportClassMetadata($metadata));
     $output->writeln('Done!');
 }
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $bundleClass = null;
     $bundleDirs = $this->container->getKernelService()->getBundleDirs();
     foreach ($this->container->getKernelService()->getBundles() as $bundle) {
         if (strpos(get_class($bundle), $input->getArgument('bundle')) !== false) {
             $tmp = dirname(str_replace('\\', '/', get_class($bundle)));
             $namespace = str_replace('/', '\\', dirname($tmp));
             $class = basename($tmp);
             if (isset($bundleDirs[$namespace])) {
                 $destPath = realpath($bundleDirs[$namespace]) . '/' . $class;
                 $bundleClass = $class;
                 break;
             }
         }
     }
     $type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
     if ($type === 'annotation') {
         $destPath .= '/Entities';
     } else {
         $destPath .= '/Resources/config/doctrine/metadata';
     }
     // adjust so file naming works
     if ($type === 'yaml') {
         $type = 'yml';
     }
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type);
     if ($type === 'annotation') {
         $entityGenerator = $this->getEntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     $converter = new ConvertDoctrine1Schema($input->getArgument('d1-schema'));
     $metadata = $converter->getMetadata();
     if ($metadata) {
         $output->writeln(sprintf('Converting Doctrine 1 schema "<info>%s</info>"', $input->getArgument('d1-schema')));
         foreach ($metadata as $class) {
             $className = $class->name;
             $class->name = $namespace . '\\' . $bundleClass . '\\Entities\\' . $className;
             if ($type === 'annotation') {
                 $path = $destPath . '/' . $className . '.php';
             } else {
                 $path = $destPath . '/' . str_replace('\\', '.', $class->name) . '.dcm.' . $type;
             }
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
             $code = $exporter->exportClassMetadata($class);
             if (!is_dir($dir = dirname($path))) {
                 mkdir($dir, 0777, true);
             }
             file_put_contents($path, $code);
         }
     } else {
         $output->writeln('Database does not have any mapping information.' . PHP_EOL, 'ERROR');
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle'));
     $destPath = $bundle->getPath();
     /*  $type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
         if ('annotation' === $type) {
             $destPath .= '/Entity/Base';
         } else {
             $destPath .= '/Resources/config/doctrine';
         }
         if ('yaml' === $type) {
             $type = 'yml';
         }*/
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type);
     $exporter->setOverwriteExistingFiles($input->getOption('force'));
     if ('annotation' === $type) {
         $entityGenerator = $this->getEntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     $em = $this->getEntityManager($input->getOption('em'));
     $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
     $em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
     $emName = $input->getOption('em');
     $emName = $emName ? $emName : 'default';
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     $metadata = MetadataFilter::filter($metadata, $input->getOption('filter'));
     if ($metadata) {
         $output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', $emName));
         foreach ($metadata as $class) {
             $className = $class->name;
             $class->name = $bundle->getNamespace() . '\\Entity\\Base\\' . $className;
             if ('annotation' === $type) {
                 $path = $destPath . '/' . $className . '.php';
             } else {
                 $path = $destPath . '/' . $className . '.orm.' . $type;
             }
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
             $code = $exporter->exportClassMetadata($class);
             if (!is_dir($dir = dirname($path))) {
                 mkdir($dir, 0777, true);
             }
             $code = str_replace('private $', 'protected $', $code);
             file_put_contents($path, $code);
             $mainFilePath = $destPath . '/../' . $className . '.php';
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $mainFilePath));
             file_put_contents($mainFilePath, '<?php' . "\n\n" . 'namespace ' . $bundle->getNamespace() . '\\Entity;' . "\n\n" . 'use ' . $bundle->getNamespace() . '\\Entity\\Base\\' . $className . ' as Base' . $className . ';' . "\n\n" . 'class ' . $className . ' extends Base' . $className . "\n" . '{' . "\n" . '}');
         }
     } else {
         $output->writeln('Database does not have any mapping information.', 'ERROR');
         $output->writeln('', 'ERROR');
     }
 }
 /**
  * @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);
 }
 /**
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $em = $this->getHelper('em')->getEntityManager();
     // Process source directories
     $fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from'));
     foreach ($fromPaths as &$dirName) {
         $dirName = realpath($dirName);
         if (!file_exists($dirName)) {
             throw new \InvalidArgumentException(sprintf("Doctrine 1.X schema directory '<info>%s</info>' does not exist.", $dirName));
         } else {
             if (!is_readable($dirName)) {
                 throw new \InvalidArgumentException(sprintf("Doctrine 1.X schema directory '<info>%s</info>' does not have read permissions.", $dirName));
             }
         }
     }
     // Process destination directory
     $destPath = realpath($input->getArgument('dest-path'));
     if (!file_exists($destPath)) {
         throw new \InvalidArgumentException(sprintf("Doctrine 2.X mapping destination directory '<info>%s</info>' does not exist.", $destPath));
     } else {
         if (!is_writable($destPath)) {
             throw new \InvalidArgumentException(sprintf("Doctrine 2.X mapping destination directory '<info>%s</info>' does not have write permissions.", $destPath));
         }
     }
     $toType = $input->getArgument('to-type');
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($toType, $destPath);
     if (strtolower($toType) === 'annotation') {
         $entityGenerator = new EntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
         $entityGenerator->setNumSpaces($input->getOption('num-spaces'));
         if (($extend = $input->getOption('extend')) !== null) {
             $entityGenerator->setClassToExtend($extend);
         }
     }
     $converter = new ConvertDoctrine1Schema($fromPaths);
     $metadata = $converter->getMetadata();
     if ($metadata) {
         $output->write(PHP_EOL);
         foreach ($metadata as $class) {
             $output->write(sprintf('Processing entity "<info>%s</info>"', $class->name) . PHP_EOL);
         }
         $exporter->setMetadata($metadata);
         $exporter->export();
         $output->write(PHP_EOL . sprintf('Converting Doctrine 1.X schema to "<info>%s</info>" mapping type in "<info>%s</info>"', $toType, $destPath));
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
 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);
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $bundle = $this->application->getKernel()->getBundle($input->getArgument('bundle'));
     $destPath = $bundle->getPath();
     $type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
     if ('annotation' === $type) {
         $destPath .= '/Entity';
     } else {
         $destPath .= '/Resources/config/doctrine/metadata/orm';
     }
     if ('yaml' === $type) {
         $type = 'yml';
     }
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type);
     if ('annotation' === $type) {
         $entityGenerator = $this->getEntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     $em = $this->getEntityManager($this->container, $input->getOption('em'));
     $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
     $em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     if ($metadata) {
         $output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', $emName));
         foreach ($metadata as $class) {
             $className = $class->name;
             $class->name = $bundle->getNamespace() . '\\Entity\\' . $className;
             if ('annotation' === $type) {
                 $path = $destPath . '/' . $className . '.php';
             } else {
                 $path = $destPath . '/' . str_replace('\\', '.', $class->name) . '.dcm.' . $type;
             }
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
             $code = $exporter->exportClassMetadata($class);
             if (!is_dir($dir = dirname($path))) {
                 mkdir($dir, 0777, true);
             }
             file_put_contents($path, $code);
         }
     } else {
         $output->writeln('Database does not have any mapping information.' . PHP_EOL, 'ERROR');
     }
 }
 /**
  * @param BundleInterface $bundle
  * @param string          $entity
  * @param string          $format
  * @param array           $fields
  *
  * @return EntityGeneratorResult
  *
  * @throws \Doctrine\ORM\Tools\Export\ExportException
  */
 public function generate(BundleInterface $bundle, $entity, $format, array $fields)
 {
     // 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);
     $class->customRepositoryClassName = str_replace('\\Entity\\', '\\Repository\\', $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);
         $class->setPrimaryTable(array('name' => Inflector::tableize($entity)));
         $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);
     }
     $entityCode = str_replace(array("@var integer\n", "@var boolean\n", "@param integer\n", "@param boolean\n", "@return integer\n", "@return boolean\n"), array("@var int\n", "@var bool\n", "@param int\n", "@param bool\n", "@return int\n", "@return bool\n"), $entityCode);
     $this->filesystem->mkdir(dirname($entityPath));
     file_put_contents($entityPath, $entityCode);
     if ($mappingPath) {
         $this->filesystem->mkdir(dirname($mappingPath));
         file_put_contents($mappingPath, $mappingCode);
     }
     $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\'));
     $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path);
     $repositoryPath = $path . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class->customRepositoryClassName) . '.php';
     return new EntityGeneratorResult($entityPath, $repositoryPath, $mappingPath);
 }
 /**
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $em = $this->getHelper('em')->getEntityManager();
     if ($input->getOption('from-database') === true) {
         $em->getConfiguration()->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager()));
     }
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     $metadata = MetadataFilter::filter($metadata, $input->getOption('filter'));
     // Process destination directory
     if (!is_dir($destPath = $input->getArgument('dest-path'))) {
         mkdir($destPath, 0777, true);
     }
     $destPath = realpath($destPath);
     if (!file_exists($destPath)) {
         throw new \InvalidArgumentException(sprintf("Mapping destination directory '<info>%s</info>' does not exist.", $destPath));
     } else {
         if (!is_writable($destPath)) {
             throw new \InvalidArgumentException(sprintf("Mapping destination directory '<info>%s</info>' does not have write permissions.", $destPath));
         }
     }
     $toType = strtolower($input->getArgument('to-type'));
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($toType, $destPath);
     if ($toType == 'annotation') {
         $entityGenerator = new EntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
         $entityGenerator->setNumSpaces($input->getOption('num-spaces'));
         if (($extend = $input->getOption('extend')) !== null) {
             $entityGenerator->setClassToExtend($extend);
         }
     }
     if (count($metadata)) {
         foreach ($metadata as $class) {
             $output->write(sprintf('Processing entity "<info>%s</info>"', $class->name) . PHP_EOL);
         }
         $exporter->setMetadata($metadata);
         $exporter->export();
         $output->write(PHP_EOL . sprintf('Exporting "<info>%s</info>" mapping information to "<info>%s</info>"' . PHP_EOL, $toType, $destPath));
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function generate($resourceName, OutputInterface $output = null)
 {
     if (!$this->_initialized) {
         $this->buildDefaultConfiguration($resourceName, $output);
     }
     $entityClass = $this->configuration['namespace'] . '\\' . $this->model;
     $modelPath = $this->configuration['directory'] . '/' . $this->model . '.php';
     if (file_exists($modelPath)) {
         $this->addError(sprintf('Model "%s" already exist.', $modelPath));
         return false;
     }
     $class = new ClassMetadataInfo($entityClass);
     $class->isMappedSuperclass = true;
     $class->setPrimaryTable(array('name' => strtolower($this->model)));
     $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     foreach ($this->configuration['fields'] as $field) {
         $class->mapField($field);
     }
     $entityGenerator = $this->getEntityGenerator();
     if ($this->configuration['with_interface']) {
         $fields = $this->getFieldsFromMetadata($class);
         $this->renderFile('model/ModelInterface.php.twig', $this->configuration['directory'] . '/' . $this->model . 'Interface.php', array('fields' => $fields, 'namespace' => $this->configuration['namespace'], 'class_name' => $this->model . 'Interface'));
     }
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter('yml' == $this->configuration['format'] ? 'yaml' : $this->configuration['format']);
     $mappingPath = $this->bundle->getPath() . '/Resources/config/doctrine/model/' . $this->model . '.orm.' . $this->configuration['format'];
     if (file_exists($mappingPath)) {
         $this->addError(sprintf('Cannot generate model when mapping "%s" already exists.', $mappingPath));
         return false;
     }
     $mappingCode = $exporter->exportClassMetadata($class);
     $entityGenerator->setGenerateAnnotations(false);
     $entityCode = $entityGenerator->generateEntityClass($class);
     file_put_contents($modelPath, $entityCode);
     if ($mappingPath) {
         $this->fileSystem->mkdir(dirname($mappingPath));
         file_put_contents($mappingPath, $mappingCode);
     }
     $this->renderFile('model/Repository.php.twig', $this->bundle->getPath() . '/Doctrine/ORM/' . $this->model . 'Repository.php', array('namespace' => $this->bundle->getNamespace() . '\\Doctrine\\ORM', 'class_name' => $this->model . 'Repository'));
     $this->patchDependencyInjection();
 }
 public function run()
 {
     $arguments = $this->getArguments();
     $printer = $this->getPrinter();
     $printer->writeln(sprintf('Converting Doctrine 1 schema at "%s" to the "%s" format', $printer->format($arguments['from'], 'KEYWORD'), $printer->format($arguments['to'], 'KEYWORD')));
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($arguments['to'], $arguments['dest']);
     if ($arguments['to'] === 'annotation') {
         $entityGenerator = new EntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     $converter = new ConvertDoctrine1Schema($arguments['from']);
     $metadatas = $converter->getMetadatas();
     foreach ($metadatas as $metadata) {
         $printer->writeln(sprintf('Processing entity "%s"', $printer->format($metadata->name, 'KEYWORD')));
     }
     $exporter->setMetadatas($metadatas);
     $exporter->export();
     $printer->writeln(sprintf('Writing Doctrine 2 mapping files to "%s"', $printer->format($arguments['dest'], 'KEYWORD')));
 }
 public function run()
 {
     $arguments = $this->getArguments();
     $cme = new ClassMetadataExporter();
     $printer = $this->getPrinter();
     // Get exporter and configure it
     $exporter = $cme->getExporter($arguments['to'], $arguments['dest']);
     if (isset($arguments['extend']) && $arguments['extend']) {
         $exporter->setClassToExtend($arguments['extend']);
     }
     if (isset($arguments['num-spaces']) && $arguments['extend']) {
         $exporter->setNumSpaces($arguments['num-spaces']);
     }
     $from = (array) $arguments['from'];
     if ($this->_isDoctrine1Schema($from)) {
         $printer->writeln('Converting Doctrine 1 schema to Doctrine 2 mapping files', 'INFO');
         $converter = new \Doctrine\ORM\Tools\ConvertDoctrine1Schema($from);
         $metadatas = $converter->getMetadatasFromSchema();
     } else {
         foreach ($from as $source) {
             $sourceArg = $source;
             $type = $this->_determineSourceType($sourceArg);
             if (!$type) {
                 throw CliException::invalidMappingSourceType($sourceArg);
             }
             $source = $this->_getSourceByType($type, $sourceArg);
             $printer->writeln(sprintf('Adding "%s" mapping source which contains the "%s" format', $printer->format($sourceArg, 'KEYWORD'), $printer->format($type, 'KEYWORD')));
             $cme->addMappingSource($source, $type);
         }
         $metadatas = $cme->getMetadatasForMappingSources();
     }
     foreach ($metadatas as $metadata) {
         $printer->writeln(sprintf('Processing entity "%s"', $printer->format($metadata->name, 'KEYWORD')));
     }
     $printer->writeln(sprintf('Exporting "%s" mapping information to directory "%s"', $printer->format($arguments['to'], 'KEYWORD'), $printer->format($arguments['dest'], 'KEYWORD')));
     $exporter->setMetadatas($metadatas);
     $exporter->export();
 }
 /**
  * @depends testExportDirectoryAndFilesAreCreated
  */
 public function testExportedMetadataCanBeReadBackIn()
 {
     $type = $this->_getType();
     $cme = new ClassMetadataExporter();
     $cme->addMappingSource(__DIR__ . '/export/' . $type, $type);
     $metadataInstances = $cme->getMetadatas();
     $metadata = current($metadataInstances);
     $this->assertEquals($this->_getTestEntityName(), $metadata->name);
     return $metadata;
 }
 public function testExportDirectoryAndFilesAreCreated()
 {
     $type = $this->_getType();
     $metadataDriver = $this->_createMetadataDriver($type, __DIR__ . '/' . $type);
     $em = $this->_createEntityManager($metadataDriver);
     $cmf = $this->_createClassMetadataFactory($em, $type);
     $metadata = $cmf->getAllMetadata();
     $metadata[0]->name = 'Doctrine\\Tests\\ORM\\Tools\\Export\\ExportedUser';
     $this->assertEquals('Doctrine\\Tests\\ORM\\Tools\\Export\\ExportedUser', $metadata[0]->name);
     $type = $this->_getType();
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type, __DIR__ . '/export/' . $type);
     if ($type === 'annotation') {
         $entityGenerator = new EntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     $this->_extension = $exporter->getExtension();
     $exporter->setMetadata($metadata);
     $exporter->export();
     if ($type == 'annotation') {
         $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/' . str_replace('\\', '/', 'Doctrine\\Tests\\ORM\\Tools\\Export\\ExportedUser') . $this->_extension));
     } else {
         $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/Doctrine.Tests.ORM.Tools.Export.ExportedUser' . $this->_extension));
     }
 }
Example #20
0
    /**
     * @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle/MySampleBundle")
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $entity = str_replace('/', '\\', $input->getArgument('entity'));

        if (false === $pos = strpos($entity, ':')) {
            throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity));
        }

        $bundleName = substr($entity, 0, $pos);
        $bundle = $this->getApplication()->getKernel()->getBundle($bundleName);

        // we need to create the directory so that the command works even
        // for the very first entity created in the bundle
        if (!is_dir($bundle->getPath().'/Entity')) {
            @mkdir($bundle->getPath().'/Entity', 0777, true);
        }

        $entity = substr($entity, $pos + 1);
        $fullEntityClassName = $this->container->get('doctrine')->getEntityNamespace($bundleName).'\\'.$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
        if ($fields = $input->getArgument('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));
                }
            }
        }

        $entityPath = $bundle->getPath().'/Entity/'.str_replace('\\', '/', $entity).'.php';
        if (file_exists($entityPath)) {
            throw new \RuntimeException(sprintf('Entity "%s" already exists.', $class->name));
        }

        $entityGenerator = $this->getEntityGenerator();
        if ('annotation' === $mappingType) {
            $entityGenerator->setGenerateAnnotations(true);
            $entityCode = $entityGenerator->generateEntityClass($class);
            $mappingPath = $mappingCode = false;
        } else {
            // Setup a new exporter for the mapping type specified
            $cme = new ClassMetadataExporter();
            $exporter = $cme->getExporter($mappingType);
            $mappingType = 'yaml' == $mappingType ? 'yml' : $mappingType;
            $mappingPath = $bundle->getPath().'/Resources/config/doctrine/'.str_replace('\\', '.', $entity).'.orm.'.$mappingType;
            $mappingCode = $exporter->exportClassMetadata($class);

            $entityGenerator->setGenerateAnnotations(false);
            $entityCode = $entityGenerator->generateEntityClass($class);

            if (file_exists($mappingPath)) {
                throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" 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);
        }
    }
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $app = $this->getHelper("app")->getApplication();
     $registry = $app['orm.manager_registry'];
     /* @var $registry ManagerRegistry */
     $emName = $input->getOption("em") ? $input->getOption("em") : "default";
     $em = $registry->getManager($emName);
     //$bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle'));
     //        $destPath = $bundle->getPath();
     $destPath = $input->getArgument("path");
     $type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
     if ('annotation' === $type) {
         $destPath .= "/" . preg_replace("#\\\\#", "/", $input->getOption("namespace"));
     } else {
         $destPath .= '/Resources/doctrine';
     }
     if ('yaml' === $type) {
         $type = 'yml';
     }
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type);
     $exporter->setOverwriteExistingFiles($input->getOption('force'));
     if ('annotation' === $type) {
         $entityGenerator = $this->getEntityGenerator();
         $exporter->setEntityGenerator($entityGenerator);
     }
     //$em = $this->getEntityManager($input->getOption('em'));
     $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
     $em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
     //$emName = $input->getOption('em');
     //        $emName = $emName ? $emName : 'default';
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     $metadata = MetadataFilter::filter($metadata, $input->getOption('filter'));
     if ($metadata) {
         $output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', $emName));
         foreach ($metadata as $class) {
             $className = $class->name;
             $class->name = $input->getOption("namespace") . "\\" . $className;
             //$classPath = $class-> /* todo fix it */
             if ('annotation' === $type) {
                 $path = $destPath . '/' . $className . '.php';
             } else {
                 $path = $destPath . '/' . preg_replace('#\\\\#', ".", $class->name) . '.dcm.' . $type;
             }
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
             $code = $exporter->exportClassMetadata($class);
             if (!is_dir($dir = dirname($path))) {
                 mkdir($dir, 0777, true);
             }
             file_put_contents($path, $code);
         }
     } else {
         $output->writeln('Database does not have any mapping information.', 'ERROR');
         $output->writeln('', 'ERROR');
     }
 }
Example #22
0
<?php

define('DIR_BASE', realpath(dirname(__FILE__) . '/..'));
define('DIR_CORE', DIR_BASE . '/core');
define('DIR_CACHE', DIR_BASE . '/cache');
define('DIR_PACKAGES', DIR_BASE . '/packages');
define('DIR_URI', '');
require '../core/autoload.php';
require '../vendor/autoload.php';
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\DatabaseDriver;
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
new AutoLoad();
$dbConfig = Config::getInstance()->getValues('db');
$db = array('driver' => 'pdo_mysql', 'host' => $dbConfig->DB_HOST . ':' . $dbConfig->DB_PORT, 'user' => $dbConfig->DB_USER, 'password' => $dbConfig->DB_PASS, 'dbname' => $dbConfig->DB_NAME);
$doctrineConfig = Setup::createAnnotationMetadataConfiguration(array(DIR_CACHE . '/doctrine'), $dbConfig->DB_DEV);
$entityManager = EntityManager::create($db, $doctrineConfig);
$entityManager->getConnection()->connect();
$databaseDriver = new DatabaseDriver($entityManager->getConnection()->getSchemaManager());
$databaseDriver->setNamespace('Models\\');
$entityManager->getConfiguration()->setMetadataDriverImpl($databaseDriver);
$metadataFactory = new DisconnectedClassMetadataFactory();
$metadataFactory->setEntityManager($entityManager);
$metadata = $metadataFactory->getAllMetadata();
$metadataExporter = new ClassMetadataExporter();
$exporter = $metadataExporter->getExporter('xml', DIR_CACHE . '/doctrine');
$exporter->setMetadata($metadata);
$exporter->export();
echo 'Doctrine models successfully generated!';
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $em = $this->getEntityManager();
     $destPath = APP_PATH . DIRECTORY_SEPARATOR . preg_replace("#\\\\#", DIRECTORY_SEPARATOR, $this->getNamespace());
     $type = 'annotation';
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($type);
     $exporter->setOverwriteExistingFiles($input->getOption('force'));
     $exporter->setEntityGenerator($this->getEntityGenerator());
     $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
     $em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getAllMetadata();
     $metadata = MetadataFilter::filter($metadata, $input->getOption('filter'));
     if ($metadata) {
         $output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', 'default'));
         foreach ($metadata as $class) {
             $className = $class->name;
             $class->name = sprintf('%s\\%s', $this->getNamespace(), $className);
             $path = $destPath . DIRECTORY_SEPARATOR . str_replace('\\', '.', $className) . '.php';
             $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
             $code = $exporter->exportClassMetadata($class);
             if (!is_dir($dir = dirname($path))) {
                 mkdir($dir, 0775, true);
             }
             file_put_contents($path, $code);
             chmod($path, 0664);
         }
         return 0;
     } else {
         $output->writeln('Database does not have any mapping information.', 'ERROR');
         $output->writeln('', 'ERROR');
         return 1;
     }
 }
 public function generateTranslationEntity(BundleInterface $bundle, $translatableEntity, $translationEntity, $format, array $fields)
 {
     // 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()));
     $translationEntityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $translationEntity;
     $translatableEntityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $translatableEntity;
     $translationEntityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $translationEntity) . '.php';
     if (file_exists($translationEntityPath)) {
         throw new \RuntimeException(sprintf('Entity "%s" already exists.', $translationEntityClass));
     }
     $translationClass = new ClassMetadataInfo($translationEntityClass);
     $translatableClass = new ClassMetadataInfo($translatableEntityClass);
     foreach ($fields as $field) {
         $translationClass->mapField($field);
     }
     $entityGenerator = $this->getEntityGenerator();
     $entityGenerator->setClassToExtend('Prezent\\Doctrine\\Translatable\\Entity\\AbstractTranslation');
     if ('annotation' === $format) {
         $entityGenerator->setGenerateAnnotations(true);
         $entityCode = $entityGenerator->generateTranslationEntityClass($translationClass, $translatableClass);
         $mappingPath = $mappingCode = false;
     } else {
         $cme = new ClassMetadataExporter();
         $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format);
         $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $translationEntity) . '.orm.' . $format;
         if (file_exists($mappingPath)) {
             throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath));
         }
         $mappingCode = $exporter->exportClassMetadata($translationClass);
         $entityGenerator->setGenerateAnnotations(false);
         $entityCode = $entityGenerator->generateTranslationEntityClass($translationClass, $translatableClass);
     }
     $this->filesystem->mkdir(dirname($translationEntityPath));
     file_put_contents($translationEntityPath, $entityCode);
     if ($mappingPath) {
         $this->filesystem->mkdir(dirname($mappingPath));
         file_put_contents($mappingPath, $mappingCode);
     }
 }
 protected function getExporter($toType, $destPath)
 {
     $cme = new ClassMetadataExporter();
     return $cme->getExporter($toType, $destPath);
 }
 /**
  * @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle\MySampleBundle")
  * @FIXME
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Get the bundles we need
     $targetBundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle'));
     $javascriptClassBundle = $this->getApplication()->getKernel()->getBundle('JavascriptClassBundle');
     $entity = $input->getArgument('entity');
     $fullEntityClassName = $targetBundle->getNamespace() . '\\Entity\\' . $entity;
     $mappingType = $input->getOption('mapping-type');
     $framework = $input->getOption('framework') == 'from_config' ? $this->container->getParameter('nutellove_jsclass.generator.framework') : $input->getOption('framework');
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Fetching the metadata for this Bundle/Entity/Mapping-Type
     $metadatas = $this->getBundleMetadatas($targetBundle);
     //var_dump ($metadatas);
     $classMetadata = $metadatas[$fullEntityClassName];
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Setup a new exporter for the mapping type specified
     $cme = new ClassMetadataExporter();
     $exporter = $cme->getExporter($mappingType);
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Generation of the Base Mootools Entity
     $output->writeln(sprintf('Generating %s Javascript Entities for "<info>%s</info>"', $framework, $fullEntityClassName));
     $baseEntityPath = $targetBundle->getPath() . '/Resources/public/jsclass/' . strtolower($this->getJsFramework()) . '/entity/' . strtolower($targetBundle->getName()) . '/base/Base' . $entity . '.class.js';
     $baseEntityGeneratorGetter = 'get' . $framework . 'BaseEntityGenerator';
     $baseEntityGenerator = call_user_func_array(array($this, $baseEntityGeneratorGetter), array());
     //$baseEntityGenerator = $this->getMootoolsBaseEntityGenerator();
     if ('annotation' === $mappingType) {
         $exporter->setEntityGenerator($baseEntityGenerator);
         $baseEntityCode = $exporter->exportClassMetadata($classMetadata);
         //$mappingPath = $mappingCode = false;
     } else {
         $baseEntityCode = $baseEntityGenerator->generateEntityClass($classMetadata);
     }
     $output->writeln(sprintf('  > Base Js Entity for into <info>%s</info>', $baseEntityPath));
     if (file_exists($baseEntityPath)) {
         $output->writeln(sprintf('    > Already existing, overwriting.'));
         //throw new \RuntimeException(sprintf("Mootools Base Entity %s already exists.", $classMetadata->name));
     }
     if (!is_dir($dir = dirname($baseEntityPath))) {
         mkdir($dir, 0777, true);
     }
     file_put_contents($baseEntityPath, $baseEntityCode);
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Generation (if needed) of the Mootools Entity
     $entityPath = $targetBundle->getPath() . '/Resources/public/jsclass/' . strtolower($this->getJsFramework()) . '/entity/' . strtolower($targetBundle->getName()) . '/' . $entity . '.class.js';
     $entityGenerator = $this->getMootoolsEntityGenerator();
     $entityGenerator->setClassToExtend("Base" . $targetBundle->getName() . $entity);
     if ('annotation' === $mappingType) {
         $exporter->setEntityGenerator($entityGenerator);
         $entityCode = $exporter->exportClassMetadata($classMetadata);
         //$mappingPath = $mappingCode = false;
     } else {
         $entityCode = $entityGenerator->generateEntityClass($classMetadata);
     }
     $output->writeln(sprintf('  > Js Entity into <info>%s</info>', $entityPath));
     if (file_exists($entityPath)) {
         $output->writeln(sprintf('    > Already exists, left untouched'));
     } else {
         if (!is_dir($dir = dirname($entityPath))) {
             mkdir($dir, 0777, true);
         }
         file_put_contents($entityPath, $entityCode);
     }
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Generation of the Base Controller
     $output->writeln(sprintf('Generating Controllers for "<info>%s</info>"', $fullEntityClassName));
     $baseControllerPath = $javascriptClassBundle->getPath() . '/Controller/Entity/' . $targetBundle->getName() . '/Base/' . $entity . 'Controller.php';
     $baseControllerGenerator = $this->getBaseControllerGenerator();
     if ('annotation' === $mappingType) {
         $exporter->setEntityGenerator($baseControllerGenerator);
         $baseControllerCode = $exporter->exportClassMetadata($classMetadata);
         //$mappingPath = $mappingCode = false;
     } else {
         $baseControllerCode = $baseControllerGenerator->generateEntityClass($classMetadata);
     }
     $output->writeln(sprintf('  > Base Entity Controller into <info>%s</info>', $baseControllerPath));
     if (file_exists($baseControllerPath)) {
         $output->writeln(sprintf('    > Already existing, overwriting.'));
     }
     if (!is_dir($dir = dirname($baseControllerPath))) {
         mkdir($dir, 0777, true);
     }
     file_put_contents($baseControllerPath, $baseControllerCode);
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // Generation of the Controller (if needed)
     $controllerPath = $javascriptClassBundle->getPath() . '/Controller/Entity/' . $targetBundle->getName() . '/' . $entity . 'Controller.php';
     $controllerGenerator = $this->getControllerGenerator();
     if ('annotation' === $mappingType) {
         $exporter->setEntityGenerator($controllerGenerator);
         $controllerCode = $exporter->exportClassMetadata($classMetadata);
     } else {
         $controllerCode = $controllerGenerator->generateEntityClass($classMetadata);
     }
     $output->writeln(sprintf('  > Entity Controller into <info>%s</info>', $controllerPath));
     if (file_exists($controllerPath)) {
         $output->writeln(sprintf('    > Already exists, left untouched'));
     } else {
         if (!is_dir($dir = dirname($controllerPath))) {
             mkdir($dir, 0777, true);
         }
         file_put_contents($controllerPath, $controllerCode);
     }
 }