Exemplo n.º 1
0
 public function generate($jsonSchema)
 {
     $schema = json_decode($jsonSchema, true);
     if (!isset($schema['type']) && $schema['type'] !== 'object') {
         throw new \RuntimeException("Unable to process the schema");
     }
     if (!isset($schema['title'])) {
         throw new \RuntimeException("title property must be defined");
     }
     // TODO investigate implementation via ClassMetadataBuilder
     $className = $schema['title'];
     $medatadata = new ClassMetadata($this->getNamespace() . '\\' . $className);
     if (isset($schema['properties'])) {
         foreach ($schema['properties'] as $name => $definition) {
             $type = $definition['type'];
             $nullable = isset($schema['required']) ? !in_array($name, $schema['required']) : true;
             $medatadata->mapField(['fieldName' => $name, 'type' => $type, 'nullable' => $nullable, 'options' => []]);
         }
     }
     $filename = sprintf("%s/%s/%s.php", $this->getPath(), join('/', explode('\\', $this->getNamespace())), $className);
     mkdir(dirname($filename), 0777, true);
     $generator = new EntityGenerator();
     $generator->setGenerateAnnotations(true);
     file_put_contents($filename, $generator->generateEntityClass($medatadata));
 }
 protected function getEntityGenerator()
 {
     $entityGenerator = new EntityGenerator();
     $entityGenerator->setGenerateAnnotations(false);
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(false);
     $entityGenerator->setUpdateEntityIfExists(true);
     $entityGenerator->setNumSpaces(4);
     $entityGenerator->setAnnotationPrefix('ORM\\');
     return $entityGenerator;
 }
Exemplo n.º 3
0
 /**
  * generate entity objects automatically from mysql db tables
  * @return none
  */
 function generate_classes()
 {
     $this->em->getConfiguration()->setMetadataDriverImpl(new DatabaseDriver($this->em->getConnection()->getSchemaManager()));
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($this->em);
     $metadata = $cmf->getAllMetadata();
     $generator = new EntityGenerator();
     $generator->setUpdateEntityIfExists(true);
     $generator->setGenerateStubMethods(true);
     $generator->setGenerateAnnotations(true);
     $generator->generate($metadata, APPPATH . "models/Entities");
 }
Exemplo n.º 4
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $printer = $this->getPrinter();
     $arguments = $this->getArguments();
     $from = $arguments['from'];
     $dest = realpath($arguments['dest']);
     $entityGenerator = new EntityGenerator();
     $entityGenerator->setGenerateAnnotations(false);
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(false);
     $entityGenerator->setUpdateEntityIfExists(true);
     if (isset($arguments['extend']) && $arguments['extend']) {
         $entityGenerator->setClassToExtend($arguments['extend']);
     }
     if (isset($arguments['num-spaces']) && $arguments['extend']) {
         $entityGenerator->setNumSpaces($arguments['num-spaces']);
     }
     $reader = new ClassMetadataReader();
     $reader->setEntityManager($this->getConfiguration()->getAttribute('em'));
     $reader->addMappingSource($from);
     $metadatas = $reader->getMetadatas();
     foreach ($metadatas as $metadata) {
         $printer->writeln(sprintf('Processing entity "%s"', $printer->format($metadata->name, 'KEYWORD')));
     }
     $entityGenerator->generate($metadatas, $dest);
     $printer->write(PHP_EOL);
     $printer->writeln(sprintf('Entity classes generated to "%s"', $printer->format($dest, 'KEYWORD')));
 }
Exemplo n.º 5
0
 /**
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $em = $this->getHelper('em')->getEntityManager();
     if (\Zend_Registry::isRegistered(\LoSo_Zend_Application_Bootstrap_SymfonyContainerBootstrap::getRegistryIndex()) && ($container = \Zend_Registry::get(\LoSo_Zend_Application_Bootstrap_SymfonyContainerBootstrap::getRegistryIndex())) instanceof \Symfony\Component\DependencyInjection\ContainerInterface) {
         $mappingPaths = $container->getParameter('doctrine.orm.mapping_paths');
         $entitiesPaths = $container->getParameter('doctrine.orm.entities_paths');
     } else {
         $doctrineConfig = \Zend_Registry::get('doctrine.config');
         $mappingPaths = $doctrineConfig['doctrine.orm.mapping_paths'];
         $entitiesPaths = $doctrineConfig['doctrine.orm.entities_paths'];
     }
     $cmf = new DisconnectedClassMetadataFactory($em);
     $metadatas = $cmf->getAllMetadata();
     foreach ($mappingPaths as $namespace => $mappingPath) {
         // Process destination directory
         $destPath = realpath($entitiesPaths[$namespace]);
         if (!file_exists($destPath)) {
             throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not exist.", $destPath));
         } else {
             if (!is_writable($destPath)) {
                 throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not have write permissions.", $destPath));
             }
         }
         $moduleMetadatas = MetadataFilter::filter($metadatas, $namespace);
         if (count($moduleMetadatas)) {
             // Create EntityGenerator
             $entityGenerator = new EntityGenerator();
             $entityGenerator->setGenerateAnnotations($input->getOption('generate-annotations'));
             $entityGenerator->setGenerateStubMethods($input->getOption('generate-methods'));
             $entityGenerator->setRegenerateEntityIfExists($input->getOption('regenerate-entities'));
             $entityGenerator->setUpdateEntityIfExists($input->getOption('update-entities'));
             $entityGenerator->setNumSpaces($input->getOption('num-spaces'));
             if (($extend = $input->getOption('extend')) !== null) {
                 $entityGenerator->setClassToExtend($extend);
             }
             foreach ($moduleMetadatas as $metadata) {
                 $output->write(sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL);
             }
             // Generating Entities
             $entityGenerator->generate($moduleMetadatas, $destPath);
             $this->_processNamespaces($destPath, $namespace);
             // Outputting information message
             $output->write(sprintf('Entity classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
         } else {
             $output->write('No Metadata Classes to process.' . PHP_EOL);
         }
     }
     /*$output->write(PHP_EOL . 'Reset database.' . PHP_EOL);
     
             $metadatas = $em->getMetadataFactory()->getAllMetadata();
             $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em);
             $output->write('Dropping database schema...' . PHP_EOL);
             $schemaTool->dropSchema($metadatas);
             $output->write('Database schema dropped successfully!' . PHP_EOL);
             $output->write('Creating database schema...' . PHP_EOL);
             $schemaTool->createSchema($metadatas);
             $output->write('Database schema created successfully!' . PHP_EOL);*/
 }
 function testCreateSchema()
 {
     /* @var $em \Doctrine\ORM\EntityManager */
     $em = $this->app["orm.em"];
     $tool = new SchemaTool($em);
     //@note @doctrine générer les fichiers de classe à partir de métadonnées
     /* generate entity classes */
     $dmf = new DisconnectedClassMetadataFactory();
     $dmf->setEntityManager($em);
     $metadatas = $dmf->getAllMetadata();
     //print_r($metadatas);
     $generator = new EntityGenerator();
     $generator->setGenerateAnnotations(TRUE);
     $generator->setGenerateStubMethods(TRUE);
     $generator->setRegenerateEntityIfExists(TRUE);
     $generator->setUpdateEntityIfExists(TRUE);
     $generator->generate($metadatas, ROOT_TEST_DIR);
     $generator->setNumSpaces(4);
     $this->assertFileExists(ROOT_TEST_DIR . "/Entity/Post.php");
     /* @note @doctrine générer la base de donnée à partir des métadonnées */
     /* @see Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand */
     /* generate database */
     $tool->dropSchema($metadatas);
     $tool->createSchema($metadatas);
     $post = new \Entity\Post();
     $post->setTitle("the title");
     $em->persist($post);
     $em->flush();
     $this->assertInternalType("int", $post->getId());
 }
Exemplo n.º 7
0
 /**
  * @return bool
  * @throws \Exception
  */
 public function generateClass()
 {
     $metadata = $this->getMetaData();
     $this->setClassName($metadata->name);
     // setting the namespace
     $metadata->name = $this->getNamespace() . '\\' . $metadata->name;
     //generate the basic class-code
     if (!($this->generatedCode = $this->entityGenerator->generateEntityClass($metadata))) {
         throw new \Exception('Entity class could not be created');
     }
     // TableAnnotation-Update if a Database is given
     if (isset($this->database)) {
         $this->updateTableAnnotation();
     }
     $this->generateUseStatements();
     $this->generateMethods();
     $this->writeFile();
     return true;
 }
Exemplo n.º 8
0
 protected function getEntityGenerator()
 {
     $entityGenerator = new EntityGenerator();
     if (version_compare(DoctrineVersion::VERSION, "2.0.2-DEV") >= 0) {
         $entityGenerator->setAnnotationPrefix("orm:");
     }
     $entityGenerator->setGenerateAnnotations(false);
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(false);
     $entityGenerator->setUpdateEntityIfExists(true);
     $entityGenerator->setNumSpaces(4);
     return $entityGenerator;
 }
 /**
  * @param string $className
  * @param string $newClassName
  * @return string
  */
 private function writeEntityClass($className, $newClassName)
 {
     $cmf = new ClassMetadataFactory();
     $em = $this->_getTestEntityManager();
     $cmf->setEntityManager($em);
     $metadata = $cmf->getMetadataFor($className);
     $metadata->namespace = $this->_namespace;
     $metadata->name = $newClassName;
     $metadata->customRepositoryClassName = $newClassName . "Repository";
     $this->_generator->writeEntityClass($metadata, $this->_tmpDir);
     require $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $newClassName) . ".php";
 }
Exemplo n.º 10
0
 public function __construct()
 {
     try {
         $conn = array("driver" => "pdo_mysql", "host" => "localhost", "port" => "3306", "user" => "root", "password" => "", "dbname" => "controle_gastos");
         /*
         var_dump(__DIR__);
         var_dump(PP);
         exit;
         */
         $loader = new \Doctrine\Common\ClassLoader("Entities", __DIR__);
         $loader->register();
         $config = Setup::createAnnotationMetadataConfiguration(array("../../" . __DIR__ . "/app/models"), false);
         $em = EntityManager::create($conn, $config);
         $cmf = new DisconnectedClassMetadataFactory();
         $cmf->setEntityManager($em);
         $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
         $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
         $driver = new DatabaseDriver($em->getConnection()->getSchemaManager());
         $em->getConfiguration()->setMetadataDriverImpl($driver);
         $metadata = $cmf->getAllMetadata();
         $generator = new EntityGenerator();
         $generator->setGenerateAnnotations(true);
         $generator->setGenerateStubMethods(true);
         $generator->setRegenerateEntityIfExists(true);
         $generator->setUpdateEntityIfExists(true);
         $generator->generate($metadata, "../../" . __DIR__ . "/app/models");
     } catch (\Exception $e) {
         throw $e;
     }
 }
Exemplo n.º 11
0
 public function testRegenerateEntityClass()
 {
     $metadata = $this->generateBookEntityFixture();
     $this->loadEntityClass($metadata);
     $className = basename(str_replace('\\', '/', $metadata->name));
     $path = $this->_tmpDir . '/' . $this->_namespace . '/' . $className . '.php';
     $classTest = file_get_contents($path);
     $this->_generator->setRegenerateEntityIfExists(true);
     $this->_generator->setBackupExisting(false);
     $this->_generator->writeEntityClass($metadata, $this->_tmpDir);
     $classNew = file_get_contents($path);
     $this->assertSame($classTest, $classNew);
 }
 /**
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $em = $this->getHelper('em')->getEntityManager();
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadatas = $cmf->getAllMetadata();
     $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter'));
     // Process destination directory
     $destPath = realpath($input->getArgument('dest-path'));
     if (!file_exists($destPath)) {
         throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not exist.", $input->getArgument('dest-path')));
     } else {
         if (!is_writable($destPath)) {
             throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not have write permissions.", $destPath));
         }
     }
     if (count($metadatas)) {
         // Create EntityGenerator
         $entityGenerator = new EntityGenerator();
         $entityGenerator->setGenerateAnnotations($input->getOption('generate-annotations'));
         $entityGenerator->setGenerateStubMethods($input->getOption('generate-methods'));
         $entityGenerator->setRegenerateEntityIfExists($input->getOption('regenerate-entities'));
         $entityGenerator->setUpdateEntityIfExists($input->getOption('update-entities'));
         $entityGenerator->setNumSpaces($input->getOption('num-spaces'));
         if (($extend = $input->getOption('extend')) !== null) {
             $entityGenerator->setClassToExtend($extend);
         }
         foreach ($metadatas as $metadata) {
             $output->write(sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL);
         }
         // Generating Entities
         $entityGenerator->generate($metadatas, $destPath);
         // Outputting information message
         $output->write(PHP_EOL . sprintf('Entity classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
Exemplo n.º 13
0
 /**
  * Get entity generator.
  *
  * @return EntityGenerator
  */
 protected static function getEntityGenerator()
 {
     $entityGenerator = new EntityGenerator();
     $entityGenerator->setGenerateAnnotations(true);
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(true);
     $entityGenerator->setUpdateEntityIfExists(true);
     $entityGenerator->setNumSpaces(4);
     $entityGenerator->setAnnotationPrefix(self::$annotationPrefix);
     return $entityGenerator;
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function exportClassMetadata(ClassMetadataInfo $metadata)
 {
     if (!$this->_entityGenerator) {
         throw new \RuntimeException('For the AnnotationExporter you must set an EntityGenerator instance with the setEntityGenerator() method.');
     }
     $this->_entityGenerator->setGenerateAnnotations(true);
     $this->_entityGenerator->setGenerateStubMethods(false);
     $this->_entityGenerator->setRegenerateEntityIfExists(false);
     $this->_entityGenerator->setUpdateEntityIfExists(false);
     return $this->_entityGenerator->generateEntityClass($metadata);
 }
Exemplo n.º 15
0
 public function fire()
 {
     $this->info('Starting entities generation....');
     // flush all generated and cached entities, etc
     \D2Cache::flushAll();
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($this->d2em);
     $metadata = $cmf->getAllMetadata();
     if (empty($metadata)) {
         $this->error('No metadata found to generate entities.');
         return -1;
     }
     $directory = Config::get('d2doctrine.paths.entities');
     if (!$directory) {
         $this->error('The entity directory has not been set.');
         return -1;
     }
     $entityGenerator = new EntityGenerator();
     $entityGenerator->setGenerateAnnotations($this->option('generate-annotations'));
     $entityGenerator->setGenerateStubMethods($this->option('generate-methods'));
     $entityGenerator->setRegenerateEntityIfExists($this->option('regenerate-entities'));
     $entityGenerator->setUpdateEntityIfExists($this->option('update-entities'));
     $entityGenerator->setNumSpaces($this->option('num-spaces'));
     $entityGenerator->setBackupExisting(!$this->option('no-backup'));
     $this->info('Processing entities:');
     foreach ($metadata as $item) {
         $this->line($item->name);
     }
     try {
         $entityGenerator->generate($metadata, $directory);
         $this->info('Entities have been created.');
     } catch (\ErrorException $e) {
         if ($this->option('verbose') == 3) {
             throw $e;
         }
         $this->error("Caught ErrorException: " . $e->getMessage());
         $this->info("Re-optimizing:");
         $this->call('optimize');
         $this->comment("*** You must now rerun this artisan command ***");
         exit(-1);
     }
 }
Exemplo n.º 16
0
 /**
  * @group DDC-1784
  */
 public function testGenerateEntityWithSequenceGenerator()
 {
     $metadata = new ClassMetadataInfo($this->_namespace . '\\DDC1784Entity');
     $metadata->namespace = $this->_namespace;
     $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE);
     $metadata->setSequenceGeneratorDefinition(array('sequenceName' => 'DDC1784_ID_SEQ', 'allocationSize' => 1, 'initialValue' => 2));
     $this->_generator->writeEntityClass($metadata, $this->_tmpDir);
     $filename = $this->_tmpDir . DIRECTORY_SEPARATOR . $this->_namespace . DIRECTORY_SEPARATOR . 'DDC1784Entity.php';
     $this->assertFileExists($filename);
     require_once $filename;
     $reflection = new \ReflectionProperty($metadata->name, 'id');
     $docComment = $reflection->getDocComment();
     $this->assertContains('@Id', $docComment);
     $this->assertContains('@Column(name="id", type="integer")', $docComment);
     $this->assertContains('@GeneratedValue(strategy="SEQUENCE")', $docComment);
     $this->assertContains('@SequenceGenerator(sequenceName="DDC1784_ID_SEQ", allocationSize=1, initialValue=2)', $docComment);
 }
Exemplo n.º 17
0
 /**
  * @group DDC-2079
  */
 public function testGenerateEntityWithMultipleInverseJoinColumns()
 {
     $metadata = new ClassMetadataInfo($this->_namespace . '\\DDC2079Entity');
     $metadata->namespace = $this->_namespace;
     $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE);
     $metadata->mapManyToMany(array('fieldName' => 'centroCustos', 'targetEntity' => 'DDC2079CentroCusto', 'joinTable' => array('name' => 'unidade_centro_custo', 'joinColumns' => array(array('name' => 'idorcamento', 'referencedColumnName' => 'idorcamento'), array('name' => 'idunidade', 'referencedColumnName' => 'idunidade')), 'inverseJoinColumns' => array(array('name' => 'idcentrocusto', 'referencedColumnName' => 'idcentrocusto'), array('name' => 'idpais', 'referencedColumnName' => 'idpais')))));
     $this->_generator->writeEntityClass($metadata, $this->_tmpDir);
     $filename = $this->_tmpDir . DIRECTORY_SEPARATOR . $this->_namespace . DIRECTORY_SEPARATOR . 'DDC2079Entity.php';
     $this->assertFileExists($filename);
     require_once $filename;
     $property = new \ReflectionProperty($metadata->name, 'centroCustos');
     $docComment = $property->getDocComment();
     //joinColumns
     $this->assertContains('@JoinColumn(name="idorcamento", referencedColumnName="idorcamento"),', $docComment);
     $this->assertContains('@JoinColumn(name="idunidade", referencedColumnName="idunidade")', $docComment);
     //inverseJoinColumns
     $this->assertContains('@JoinColumn(name="idcentrocusto", referencedColumnName="idcentrocusto"),', $docComment);
     $this->assertContains('@JoinColumn(name="idpais", referencedColumnName="idpais")', $docComment);
 }
 public function generate($parameters)
 {
     if (!$this->isInitialized) {
         throw new \RuntimeException('Entity generator needs to be initialized first in order to generate');
     }
     $moduleName = $this->moduleName;
     $parentClassName = $this->parentClassName;
     $this->classNames = $parameters->classNames;
     $classNames = $this->classNames;
     $outputList = array();
     $metadatas = array();
     foreach ($classNames as $className) {
         if (in_array($className, $this->driver->getAllClassNames())) {
             $classNameWithNamespace = $this->getNamespacedClassName($className);
             $this->namespacedClassNames[$className] = $classNameWithNamespace;
             $realClassNameWithNamespace = $this->composeFullClassName($classNameWithNamespace);
             $realClassName = $this->getClassNameFromNamespacedClassName($classNameWithNamespace);
             $namespace = $this->getNamespaceFromNamespacedClassName($realClassNameWithNamespace, $realClassName);
             $metadata = new \Doctrine\ORM\Mapping\ClassMetadataInfo($className);
             $this->driver->loadMetadataForClass($className, $metadata);
             $metadata = $this->fixMetadata($metadata);
             $outputList[] = array('outputDirectory' => $this->generatedEntityOutputDirectory, 'entityNamespace' => $this->entityNamespace, 'entityName' => $className, 'className' => $realClassName);
             $metadata->name = $realClassNameWithNamespace;
             $metadata->namespace = $namespace;
             $metadatas[] = $metadata;
             echo $namespace . '\\' . $realClassName . '<br>';
         }
     }
     if (count($metadatas) > 0) {
         $this->initGenerator();
         if ($this->parentClassName != null) {
             if (!file_exists($this->generatedEntityOutputDirectory . '/' . $this->parentClassName . '.php')) {
                 $parentMetadata = new \Doctrine\ORM\Mapping\ClassMetadataInfo($this->parentClassName);
                 $parentMetadata->name = $this->composeFullClassName($this->parentClassName);
                 $this->generator->writeEntityClass($parentMetadata, $this->generatedEntityOutputDirectory);
             }
         }
         $this->generator->generate($metadatas, $this->generatedEntityOutputDirectory);
     }
     return $outputList;
 }
 protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
 {
     if (strtolower($fieldName) === 'id') {
         return '';
     } else {
         return parent::generateEntityStubMethod($metadata, $type, $fieldName, $typeHint, $defaultValue);
     }
 }
 /**
  * main method
  *
  * @return void
  */
 public function main()
 {
     static $em;
     if ($em === null) {
         $wd = getcwd();
         $zf = $this->project->getProperty('zf');
         $application = (require $zf);
         if (!$application instanceof Application) {
             throw new BuildException(sprintf('zf bootstrap file "%s" should return an instance of Zend\\Mvc\\Application', $zf));
         }
         chdir($wd);
         $em = $application->getServiceManager()->get($this->em);
     }
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadatas = $cmf->getAllMetadata();
     if (!empty($this->filter)) {
         $metadatas = MetadataFilter::filter($metadatas, $this->filter);
     }
     if (count($metadatas)) {
         // Create EntityGenerator
         $entityGenerator = new EntityGenerator();
         $entityGenerator->setGenerateAnnotations(true);
         $entityGenerator->setGenerateStubMethods(true);
         $entityGenerator->setRegenerateEntityIfExists(true);
         $entityGenerator->setUpdateEntityIfExists(true);
         $entityGenerator->setNumSpaces(4);
         foreach ($metadatas as $metadata) {
             $this->log(sprintf('Processing entity %s', $metadata->name));
         }
         // Generating Entities
         $entityGenerator->generate($metadatas, $this->output);
         // Outputting information message
         $this->log(sprintf('Entity classes generated to %s', $this->output));
     } else {
         $this->log('No metadata classes to process');
     }
 }
Exemplo n.º 21
0
 /**
  * {@inheritdoc}
  */
 public function generateEntityClass(ClassMetadataInfo $metadata)
 {
     $code = parent::generateEntityClass($metadata);
     $class = new \ReflectionClass('Doctrine\\ORM\\Tools\\EntityGenerator');
     $spacesProperty = $class->getProperty('spaces');
     $spacesProperty->setAccessible(true);
     $prefixCodeWithSpacesMethod = $class->getMethod('prefixCodeWithSpaces');
     $prefixCodeWithSpacesMethod->setAccessible(true);
     $code = str_replace(array('<constants>'), array($prefixCodeWithSpacesMethod->invoke($this, $this->generateConstant($metadata))), $code);
     return str_replace('<spaces>', $spacesProperty->getValue($this), $code);
 }
 /**
  * Get a Doctrine EntityGenerator instance.
  *
  * @param string|null $classToExtend
  *
  * @return EntityGenerator
  */
 protected function getEntityGenerator($classToExtend = null)
 {
     $entityGenerator = new EntityGenerator();
     if (!is_null($classToExtend)) {
         $entityGenerator->setClassToExtend($classToExtend);
     }
     $entityGenerator->setGenerateAnnotations(true);
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(false);
     $entityGenerator->setUpdateEntityIfExists(true);
     $entityGenerator->setNumSpaces(4);
     $entityGenerator->setAnnotationPrefix('ORM\\');
     return $entityGenerator;
 }
Exemplo n.º 23
0
 /**
  * Entidades::generador()
  * 
  * Genera el proceso correspondiente 
  * @param array $metadata
  * @return void
  */
 private function generador($metadata = false)
 {
     $generator = new EntityGenerator();
     $generator->setAnnotationPrefix('');
     // edit: quick fix for No Metadata Classes to process
     $generator->setUpdateEntityIfExists(true);
     // only update if class already exists
     $generator->setRegenerateEntityIfExists(true);
     // this will overwrite the existing classes
     $generator->setGenerateStubMethods(true);
     $generator->setGenerateAnnotations(true);
     $generator->generate($metadata, dirname($this->dirEntidades));
 }
 public function testExportDirectoryAndFilesAreCreated()
 {
     $this->_deleteDirectory(__DIR__ . '/export/' . $this->_getType());
     $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();
         $entityGenerator->setAnnotationPrefix("");
         $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));
     }
 }
$classLoader = new \Doctrine\Common\ClassLoader('Symfony', realpath(__DIR__ . "/Doctrine/Symfony/"));
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Entities', realpath(__DIR__));
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Proxies', realpath(__DIR__));
$classLoader->register();
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
$annotationDriver = $config->newDefaultAnnotationDriver(array(__DIR__ . "/Entities"));
$config->setMetadataDriverImpl($annotationDriver);
$config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$connectionOptions = array('dbname' => 'application', 'user' => 'root', 'password' => '', 'host' => 'localhost', 'driver' => 'pdo_mysql');
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$databaseDriver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager());
$em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($em);
$cmf->setEntityManager($em);
$conn = $em->getConnection();
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('longblob', 'text');
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('blob', 'text');
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('varbinary', 'text');
$metadatas = $cmf->getAllMetadata();
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array('db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)));
$generator = new EntityGenerator();
$generator->setUpdateEntityIfExists(true);
$generator->setGenerateStubMethods(true);
$generator->setGenerateAnnotations(true);
$generator->generate($metadatas, __DIR__ . '../application/Entities');
 protected function getEntityGenerator()
 {
     $entityGenerator = new EntityGenerator();
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(true);
     $entityGenerator->setBackupExisting(true);
     return $entityGenerator;
 }
 /**
  * @return \Doctrine\ORM\Tools\EntityGenerator
  */
 protected function getEntityGenerator()
 {
     $entityGenerator = new EntityGenerator();
     $entityGenerator->setClassToExtend('Kunstmaan\\AdminBundle\\Entity\\AbstractEntity');
     $entityGenerator->setGenerateAnnotations(true);
     $entityGenerator->setGenerateStubMethods(true);
     $entityGenerator->setRegenerateEntityIfExists(false);
     $entityGenerator->setUpdateEntityIfExists(true);
     $entityGenerator->setNumSpaces(4);
     $entityGenerator->setAnnotationPrefix('ORM\\');
     return $entityGenerator;
 }
Exemplo n.º 28
0
 /**
  * Generate the model class for Raptor
  * Genera las clases modelos para las clases schema especificadas
  * Los modelos seran generados en el namespace especificado
  * Tenga en cuenta que un SchemaClass no es lo mismo que los nombres
  * de las tablas, es una representacion que brinda doctrine para tablas en la base de datos
  * 
  * $this->getStore()->generateClasses('\example\exampleBundle','Persona');
  * 
  * @param string $namespace el namespace del bundle donde seran creados los modelos
  * @param array $schemaClass un array con todos los schemaClass que seran generados los modelos
  */
 public function generateClasses($namespace, $schemaClass)
 {
     $clases = $schemaClass;
     // custom datatypes (not mapped for reverse engineering)
     $this->entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
     $this->entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
     // fetch metadata
     $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->entityManager->getConnection()->getSchemaManager());
     $this->entityManager->getConfiguration()->setMetadataDriverImpl($driver);
     $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($this->entityManager);
     // we must set the EntityManager
     $classes = $driver->getAllClassNames();
     $metadata = array();
     $rep = new EntityRepositoryGenerator();
     foreach ($clases as $class) {
         //any unsupported table/schema could be handled here to exclude some classes
         if (true) {
             $meta = $cmf->getMetadataFor($class);
             $association = new ItemList($meta->associationMappings);
             $me = $this;
             $association->each(function ($k, $v, $l) use(&$me) {
                 $v['targetEntity'] = $me->translateSchemas($v['targetEntity']);
                 $v['sourceEntity'] = $me->translateSchemas($v['sourceEntity']);
                 $l->set($k, $v);
             });
             $meta->associationMappings = $association->getArray();
             $real = $this->translateSchemas($class);
             $meta->name = $namespace . $this->namespaceSeparator . 'Model' . $this->namespaceSeparator . 'Entity' . $this->namespaceSeparator . $real;
             $meta->namespace = $namespace . $this->namespaceSeparator . 'Model' . $this->namespaceSeparator . 'Entity';
             // $meta->namespace='Entities\\'.$class;
             $meta->customRepositoryClassName = $namespace . $this->namespaceSeparator . 'Model' . $this->namespaceSeparator . 'Repository' . $this->namespaceSeparator . $real . 'Repository';
             //TODO buscar entidades ya creadas
             foreach ($meta->associationMappings as $key => $value) {
                 $names = $this->entityManager->getConfiguration()->getEntityNamespaces();
                 $target = $meta->associationMappings[$key]['targetEntity'];
                 $found = false;
                 foreach ($names as $routes) {
                     if ($routes[0] == '\\') {
                         $bundleRoute = substr($routes, 1);
                     } else {
                         $bundleRoute = $routes;
                     }
                     $fileroute = __DIR__ . "/../../../src/" . str_replace('\\', DIRECTORY_SEPARATOR, $bundleRoute);
                     $fileroute .= DIRECTORY_SEPARATOR . $target . ".php";
                     if (file_exists($fileroute)) {
                         $found = true;
                         $target = $bundleRoute . $this->namespaceSeparator . $value['targetEntity'];
                     }
                 }
                 if ($found) {
                     //$target = $namespace . $this->namespaceSeparator . 'Entity' . $this->namespaceSeparator . $value['targetEntity'];
                     $meta->associationMappings[$key]['targetEntity'] = $target;
                 } else {
                     $meta->associationMappings[$key]['targetEntity'] = $namespace . $this->namespaceSeparator . 'Model' . $this->namespaceSeparator . 'Entity' . $this->namespaceSeparator . $value['targetEntity'];
                 }
             }
             $metadata[] = $meta;
             $rep->writeEntityRepositoryClass($namespace . $this->namespaceSeparator . 'Model' . $this->namespaceSeparator . 'Repository' . $this->namespaceSeparator . $real . 'Repository', \Raptor\Core\Location::get(\Raptor\Core\Location::SRC));
         }
     }
     $generator = new EntityGenerator();
     $generator->setAnnotationPrefix('');
     // edit: quick fix for No Metadata Classes to process
     $generator->setUpdateEntityIfExists(true);
     // only update if class already exists
     $generator->setRegenerateEntityIfExists(true);
     // this will overwrite the existing classes
     $generator->setGenerateStubMethods(true);
     $generator->setGenerateAnnotations(true);
     //$y=new Doctrine\ORM\Tools\Export\Driver\YamlExporter(__DIR__ . '/Entities/yml');
     //$y->setMetadata($metadata);
     //$y->export();
     $generator->generate($metadata, \Raptor\Core\Location::get(\Raptor\Core\Location::SRC));
 }
Exemplo n.º 29
0
 /**
  * @param ClassMetadataInfo $metadata
  *
  * @return string
  */
 protected function generateEntityBody(ClassMetadataInfo $metadata)
 {
     $code = [];
     $code[] = $this->generateTraits($metadata);
     $code[] = parent::generateEntityBody($metadata);
     return implode("\n", $code);
 }
Exemplo n.º 30
0
 /**
  * Generate entity classes
  *
  * @param array $metadata            
  */
 protected function generateEntities(array $metadata)
 {
     $generator = new EntityGenerator();
     $generator->setGenerateAnnotations(true);
     $generator->setGenerateStubMethods(true);
     $generator->setRegenerateEntityIfExists(false);
     $generator->setUpdateEntityIfExists(true);
     $generator->setBackupExisting(false);
     if (null !== ($superclass = $this->getSuperclass())) {
         $generator->setClassToExtend($superclass);
     }
     /* @var $classMetadata \Doctrine\ORM\Mapping\ClassMetadata */
     foreach ($metadata as $classMetadata) {
         $className = end(explode('\\', $classMetadata->getName()));
         $classMetadata->setCustomRepositoryClass($this->getNsRepository() . $className);
         if (null !== ($prefix = $this->getSequencePrefix())) {
             $classMetadata->setSequenceGeneratorDefinition(array('sequenceName' => strtoupper($prefix . '_' . $className)));
         }
     }
     $generator->generate($metadata, $this->getDirectory());
 }