protected function execute(InputInterface $input, OutputInterface $output)
 {
     $bundleName = $input->getArgument('bundle');
     $filterEntity = $input->getOption('entity');
     $foundBundle = $this->findBundle($bundleName);
     if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
         $output->writeln(sprintf('Generating entity repositories for "<info>%s</info>"', $foundBundle->getName()));
         $generator = new EntityRepositoryGenerator();
         foreach ($metadatas as $metadata) {
             if ($filterEntity && $filterEntity !== $metadata->reflClass->getShortname()) {
                 continue;
             }
             if ($metadata->customRepositoryClassName) {
                 if (strpos($metadata->customRepositoryClassName, $foundBundle->getNamespace()) === false) {
                     throw new \RuntimeException("Repository " . $metadata->customRepositoryClassName . " and bundle don't have a common namespace, " . "generation failed because the target directory cannot be detected.");
                 }
                 $output->writeln(sprintf('  > <info>OK</info> generating <comment>%s</comment>', $metadata->customRepositoryClassName));
                 $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $this->findBasePathForBundle($foundBundle));
             } else {
                 $output->writeln(sprintf('  > <error>SKIP</error> no custom repository for <comment>%s</comment>', $metadata->name));
             }
         }
     } else {
         throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped entities.");
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $em = $this->getHelper('em')->getEntityManager();
     $metadatas = $em->getMetadataFactory()->getAllMetadata();
     $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter'));
     $repositoryName = $em->getConfiguration()->getDefaultRepositoryClassName();
     // 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')));
     }
     if (!is_writable($destPath)) {
         throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not have write permissions.", $destPath));
     }
     if (count($metadatas)) {
         $numRepositories = 0;
         $generator = new EntityRepositoryGenerator();
         $generator->setDefaultRepositoryName($repositoryName);
         foreach ($metadatas as $metadata) {
             if ($metadata->customRepositoryClassName) {
                 $output->writeln(sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName));
                 $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destPath);
                 $numRepositories++;
             }
         }
         if ($numRepositories) {
             // Outputting information message
             $output->writeln(PHP_EOL . sprintf('Repository classes generated to "<info>%s</INFO>"', $destPath));
         } else {
             $output->writeln('No Repository classes were found to be processed.');
         }
     } else {
         $output->writeln('No Metadata Classes to process.');
     }
 }
コード例 #3
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name'));
         $output->writeln(sprintf('Generating entities for bundle "<info>%s</info>"', $bundle->getName()));
         list($metadatas, $namespace, $path) = $this->getBundleInfo($bundle);
     } catch (\InvalidArgumentException $e) {
         $name = strtr($input->getArgument('name'), '/', '\\');
         if (false !== strpos($name, ':')) {
             $name = $this->getAliasedClassName($name);
         }
         if (class_exists($name)) {
             $output->writeln(sprintf('Generating entity "<info>%s</info>"', $name));
             list($metadatas, $namespace, $path) = $this->getClassInfo($name, $input->getOption('path'));
         } else {
             $output->writeln(sprintf('Generating entities for namespace "<info>%s</info>"', $name));
             list($metadatas, $namespace, $path) = $this->getNamespaceInfo($name, $input->getOption('path'));
         }
     }
     $generator = $this->getEntityGenerator();
     $repoGenerator = new EntityRepositoryGenerator();
     foreach ($metadatas as $metadata) {
         $output->writeln(sprintf('  > generating <comment>%s</comment>', $metadata->name));
         $generator->generate(array($metadata), $path);
         if ($metadata->customRepositoryClassName) {
             if (false === strpos($metadata->customRepositoryClassName, $namespace)) {
                 continue;
             }
             $repoGenerator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $path);
         }
     }
 }
コード例 #4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $manager = new MetadataFactory($this->container->get('doctrine'));
     try {
         $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name'));
         $output->writeln(sprintf('Generating entities for bundle "<info>%s</info>"', $bundle->getName()));
         $metadata = $manager->getBundleMetadata($bundle);
     } catch (\InvalidArgumentException $e) {
         $name = strtr($input->getArgument('name'), '/', '\\');
         if (false !== ($pos = strpos($name, ':'))) {
             $name = $this->container->get('doctrine')->getEntityNamespace(substr($name, 0, $pos)) . '\\' . substr($name, $pos + 1);
         }
         if (class_exists($name)) {
             $output->writeln(sprintf('Generating entity "<info>%s</info>"', $name));
             $metadata = $manager->getClassMetadata($name, $input->getOption('path'));
         } else {
             $output->writeln(sprintf('Generating entities for namespace "<info>%s</info>"', $name));
             $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path'));
         }
     }
     $generator = $this->getEntityGenerator();
     $generator->setBackupExisting(!$input->getOption('no-backup'));
     $repoGenerator = new EntityRepositoryGenerator();
     foreach ($metadata->getMetadata() as $m) {
         $output->writeln(sprintf('  > generating <comment>%s</comment>', $m->name));
         $generator->generate(array($m), $metadata->getPath());
         if ($m->customRepositoryClassName && false !== strpos($m->customRepositoryClassName, $metadata->getNamespace())) {
             $repoGenerator->writeEntityRepositoryClass($m->customRepositoryClassName, $metadata->getPath());
         }
     }
 }
コード例 #5
0
 public function fire()
 {
     $this->info('Starting repository generation....');
     // flush all generated and cached entities, etc
     \D2Cache::flushAll();
     try {
         $metadatas = $this->d2em->getMetadataFactory()->getAllMetadata();
     } catch (\Doctrine\Common\Persistence\Mapping\MappingException $e) {
         if ($this->option('verbose') == 3) {
             throw $e;
         }
         $this->error("Caught Doctrine\\Common\\Persistence\\Mapping\\MappingException: " . $e->getMessage());
         $this->info("Re-optimizing:");
         $this->call('optimize');
         $this->comment("*** You must now rerun this artisan command ***");
         exit(-1);
     }
     if (empty($metadatas)) {
         $this->error('No metadata found to generate entities.');
         return -1;
     }
     $directory = Config::get('d2bdoctrine.paths.repositories');
     if (!$directory) {
         $this->error('The entity directory has not been set.');
         return -1;
     }
     $numRepositories = 0;
     $generator = new EntityRepositoryGenerator();
     foreach ($metadatas as $metadata) {
         if ($metadata->customRepositoryClassName) {
             $this->line(sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName));
             $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $directory);
             $numRepositories++;
         }
     }
     if ($numRepositories) {
         $this->info('Repositories have been created.');
     } else {
         $this->info('No Repository classes were found to be processed.');
     }
 }
コード例 #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     global $container;
     /** @var string $cacheDir */
     $cacheDir = $container['doctrine.orm.repositoriesCacheDir'];
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($cacheDir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
     /** @var \SplFileInfo $file */
     foreach ($iterator as $file) {
         if ($file->isDir()) {
             rmdir($file);
         } else {
             unlink($file);
         }
     }
     /** @var EntityManager $entityManager */
     $entityManager = $container['doctrine.orm.entityManager'];
     $classMetadataFactory = new DisconnectedClassMetadataFactory();
     $classMetadataFactory->setEntityManager($entityManager);
     $metadatas = $classMetadataFactory->getAllMetadata();
     if (count($metadatas)) {
         $numRepositories = 0;
         $generator = new EntityRepositoryGenerator();
         foreach ($metadatas as $metadata) {
             if ($metadata->customRepositoryClassName) {
                 $output->write(sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName) . PHP_EOL);
                 $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $cacheDir);
                 $numRepositories++;
             }
         }
         if ($numRepositories) {
             // Outputting information message
             $output->write(PHP_EOL . sprintf('Repository classes generated to "<info>%s</INFO>"', $cacheDir) . PHP_EOL);
         } else {
             $output->write('No Repository classes were found to be processed.' . PHP_EOL);
         }
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
コード例 #7
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $generator = new EntityRepositoryGenerator();
     $kernel = $this->application->getKernel();
     $bundleDirs = $kernel->getBundleDirs();
     foreach ($kernel->getBundles() as $bundle) {
         $tmp = dirname(str_replace('\\', '/', get_class($bundle)));
         $namespace = str_replace('/', '\\', dirname($tmp));
         $class = basename($tmp);
         if (isset($bundleDirs[$namespace])) {
             $destination = realpath($bundleDirs[$namespace] . '/..');
             if ($metadatas = $this->getBundleMetadatas($bundle)) {
                 $output->writeln(sprintf('Generating entity repositories for "<info>%s</info>"', $class));
                 foreach ($metadatas as $metadata) {
                     if ($metadata->customRepositoryClassName) {
                         $output->writeln(sprintf('  > generating <comment>%s</comment>', $metadata->customRepositoryClassName));
                         $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destination);
                     }
                 }
             }
         }
     }
 }
コード例 #8
0
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     try {
         $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name'));
         $output->writeln(sprintf('Generating entities for bundle "<info>%s</info>"', $bundle->getName()));
         $metadata = $manager->getBundleMetadata($bundle);
     } catch (\InvalidArgumentException $e) {
         $name = strtr($input->getArgument('name'), '/', '\\');
         if (false !== ($pos = strpos($name, ':'))) {
             $name = $this->getContainer()->get('doctrine')->getAliasNamespace(substr($name, 0, $pos)) . '\\' . substr($name, $pos + 1);
         }
         if (class_exists($name)) {
             $output->writeln(sprintf('Generating entity "<info>%s</info>"', $name));
             $metadata = $manager->getClassMetadata($name, $input->getOption('path'));
         } else {
             $output->writeln(sprintf('Generating entities for namespace "<info>%s</info>"', $name));
             $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path'));
         }
     }
     $generator = $this->getEntityGenerator();
     $backupExisting = !$input->getOption('no-backup');
     $generator->setBackupExisting($backupExisting);
     $repoGenerator = new EntityRepositoryGenerator();
     foreach ($metadata->getMetadata() as $m) {
         if ($backupExisting) {
             $basename = substr($m->name, strrpos($m->name, '\\') + 1);
             $output->writeln(sprintf('  > backing up <comment>%s.php</comment> to <comment>%s.php~</comment>', $basename, $basename));
         }
         // Getting the metadata for the entity class once more to get the correct path if the namespace has multiple occurrences
         try {
             $entityMetadata = $manager->getClassMetadata($m->getName(), $input->getOption('path'));
         } catch (\RuntimeException $e) {
             // fall back to the bundle metadata when no entity class could be found
             $entityMetadata = $metadata;
         }
         $output->writeln(sprintf('  > generating <comment>%s</comment>', $m->name));
         $generator->generate(array($m), $entityMetadata->getPath());
         if ($m->customRepositoryClassName && false !== strpos($m->customRepositoryClassName, $metadata->getNamespace())) {
             $repoGenerator->writeEntityRepositoryClass($m->customRepositoryClassName, $metadata->getPath());
         }
     }
 }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($bundle_name = $input->getArgument('bundle')) {
            /** @var $em \Doctrine\ORM\EntityManager */
            $em = $this->getContainer()->get('doctrine')->getManager();
            $wl = $input->getOption('without-listeners');
            if ($wl) {
                $eventManager = $em->getEventManager();
                if ($eventManager->hasListeners(Events::loadClassMetadata)) {
                    foreach ($eventManager->getListeners(Events::loadClassMetadata) as $listener) {
                        $eventManager->removeEventListener(Events::loadClassMetadata, $listener);
                    }
                }
            }
            /** @var $application \Symfony\Bundle\FrameworkBundle\Console\Application */
            $application = $this->getApplication();
            $bundle = $application->getKernel()->getBundle($bundle_name);
            $output->writeln('Generating models ' . ($wl ? 'without listeners' : 'with listeners') . ' for bundle "<info>' . $bundle->getName() . '</info>"');
            $driver = null;
            /** @var $metadriver_impl \Doctrine\ORM\Mapping\Driver\DriverChain */
            $metadriver_impl = $em->getConfiguration()->getMetadataDriverImpl();
            foreach ($metadriver_impl->getDrivers() as $k => $v) {
                if (strpos($bundle->getNamespace() . '\\Entity', $k) === 0) {
                    /** @var $driver \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver */
                    $driver = $v;
                }
            }
            if (!$driver) {
                throw new \Exception('Driver not found');
            }
            /** @var $doctrine \Doctrine\Bundle\DoctrineBundle\Registry */
            $doctrine = $this->getContainer()->get('doctrine');
            $manager = new DisconnectedMetadataFactory($doctrine);
            $metadata = $manager->getBundleMetadata($bundle);
            $generator = $this->getEntityGenerator();
            $repoGenerator = new EntityRepositoryGenerator();
            foreach ($metadata->getMetadata() as $m) {
                /** @var $m \Doctrine\ORM\Mapping\ClassMetadataInfo */
                $output->writeln('  > generating ' . ($wl ? 'without listeners' : 'with listeners') . ' <comment>' . $m->getName() . '</comment>');
                $element = $driver->getElement($m->getName());
                if (isset($element['extends'])) {
                    $generator->setClassToExtend($element['extends']);
                }
                $generator->generate(array($m), $metadata->getPath());
                $generator->setClassToExtend(null);
                if ($m->customRepositoryClassName && false !== strpos($m->customRepositoryClassName, $metadata->getNamespace())) {
                    $repoGenerator->writeEntityRepositoryClass($m->customRepositoryClassName, $metadata->getPath());
                }
            }
            $modelsPath = $bundle->getPath() . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR;
            $entitiesPath = $bundle->getPath() . DIRECTORY_SEPARATOR . 'Entity' . DIRECTORY_SEPARATOR;
            if (!file_exists($modelsPath)) {
                mkdir($modelsPath);
            }
            foreach (new \DirectoryIterator($modelsPath) as $file) {
                /** @var $file \DirectoryIterator */
                if (!$file->isDot()) {
                    unlink($file->getPathname());
                }
            }
            $exists = array();
            foreach ($metadata->getMetadata() as $m) {
                /** @var $m \Doctrine\ORM\Mapping\ClassMetadataInfo */
                $element = $driver->getElement($m->getName());
                $output->writeln('  > transforming ' . ($wl ? 'without listeners' : 'with listeners') . ' <comment>' . $m->getName() . '</comment>');
                $ePath = $metadata->getPath() . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $m->getName()) . '.php';
                $ePath = realpath($ePath);
                $mPath = $modelsPath . basename($ePath);
                $eName = basename($ePath, '.php');
                $model = file_get_contents($ePath);
                if (isset($element['extends'])) {
                    $model = str_replace($element['extends'], str_replace('Entity', '@Entity', $element['extends']), $model);
                }
                $model = str_replace(' private ', ' protected ', $model);
                $model = str_replace("\n" . 'class ', "\n" . 'abstract class ', $model);
                $model = str_replace('\\Entity;', '\\Model;', $model);
                $model = str_replace('\\Entity\\' . $eName, '\\Model\\' . $eName, $model);
                if (isset($element['extends'])) {
                    $model = str_replace('@Entity', 'Entity', $model);
                }
                $model = str_replace("\n" . 'use Doctrine\\ORM\\Mapping as ORM;' . "\n", '', $model);
                $model = str_ireplace('* @preRemove', '* preRemove', $model);
                $model = str_ireplace('* @ORM\\preRemove', '* ORM\\preRemove', $model);
                $model = str_ireplace('* @postRemove', '* postRemove', $model);
                $model = str_ireplace('* @ORM\\postRemove', '* ORM\\postRemove', $model);
                $model = str_ireplace('* @prePersist', '* prePersist', $model);
                $model = str_ireplace('* @ORM\\prePersist', '* ORM\\prePersist', $model);
                $model = str_ireplace('* @postPersist', '* postPersist', $model);
                $model = str_ireplace('* @ORM\\postPersist', '* ORM\\postPersist', $model);
                $model = str_ireplace('* @preUpdate', '* preUpdate', $model);
                $model = str_ireplace('* @ORM\\preUpdate', '* ORM\\preUpdate', $model);
                $model = str_ireplace('* @postUpdate', '* postUpdate', $model);
                $model = str_ireplace('* @ORM\\postUpdate', '* ORM\\postUpdate', $model);
                $model = str_ireplace('* @postLoad', '* postLoad', $model);
                $model = str_ireplace('* @ORM\\postLoad', '* ORM\\postLoad', $model);
                $model = str_replace('* @loadClassMetadata', '* loadClassMetadata', $model);
                $model = str_replace('* @onFlush', '* onFlush', $model);
                $model = str_replace('* @var decimal', '* @var float', $model);
                $model = str_replace('* @param decimal', '* @param float', $model);
                $model = str_replace('* @return decimal', '* @return float', $model);
                $model = str_replace('* @var text', '* @var string', $model);
                $model = str_replace('* @param text', '* @param string', $model);
                $model = str_replace('* @return text', '* @return string', $model);
                $model = str_replace('* @var datetime', '* @var \\DateTime', $model);
                $model = str_replace('* @param datetime', '* @param \\DateTime', $model);
                $model = str_replace('* @return datetime', '* @return \\DateTime', $model);
                $model = str_replace('* @var My', '* @var \\My', $model);
                $model = str_replace('* @param My', '* @param \\My', $model);
                $model = str_replace('* @return My', '* @return \\My', $model);
                $model = str_replace('* @var Doctrine', '* @var \\Doctrine', $model);
                $model = str_replace('* @param Doctrine', '* @param \\Doctrine', $model);
                $model = str_replace('* @return Doctrine', '* @return \\Doctrine', $model);
                $model = preg_replace('#\\* @var enum[a-z]+#', '\\* @var string', $model);
                $model = preg_replace('#\\* @param enum[a-z]+#', '\\* @param string', $model);
                $model = preg_replace('#\\* @return enum[a-z]+#', '\\* @return string', $model);
                file_put_contents($mPath, $model);
                unlink($ePath);
                if (file_exists($ePath . '~')) {
                    rename($ePath . '~', $ePath);
                } else {
                    $bNamespace = $bundle->getNamespace();
                    $content = <<<CONTENT
<?php

namespace {$bNamespace}\\Entity;

use {$bNamespace}\\Model\\{$eName} as {$eName}Model;

class {$eName} extends {$eName}Model
{
}

CONTENT;
                    file_put_contents($ePath, $content);
                }
                $exists[] = $ePath;
            }
            foreach (new \DirectoryIterator($entitiesPath) as $file) {
                /** @var $file \DirectoryIterator */
                if (!$file->isDot() && !in_array($file->getPathname(), $exists)) {
                    unlink($file->getPathname());
                }
            }
            if ($wl) {
                $command = $application->find('doctrine:generate:models');
                $arguments = array('command' => $command->getName(), 'bundle' => $bundle_name, '--without-listeners' => false);
                $input = new ArrayInput($arguments);
                $command->run($input, $output);
            }
        } else {
            /** @var $application \Symfony\Bundle\FrameworkBundle\Console\Application */
            $application = $this->getApplication();
            $kernel = $application->getKernel();
            $srcDir = realpath($kernel->getRootDir() . '/../src');
            $bundles = $kernel->getBundles();
            foreach ($bundles as $bundle) {
                if (strlen($srcDir) > 0 && substr_compare($bundle->getPath(), $srcDir, 0, strlen($srcDir)) === 0) {
                    if (is_dir($bundle->getPath() . '/Resources/config/doctrine/')) {
                        $command = $application->find('doctrine:generate:models');
                        $arguments = array('command' => $command->getName(), 'bundle' => $bundle->getName());
                        $input = new ArrayInput($arguments);
                        $command->run($input, $output);
                    }
                }
            }
        }
    }
コード例 #10
0
 public static function generate(OutputInterface $output = null, &$reload = false)
 {
     global $container;
     /** @var string $entitiesCacheDir */
     $entitiesCacheDir = $container['doctrine.orm.entitiesCacheDir'];
     /** @var string $proxiesCacheDir */
     $proxiesCacheDir = $container['doctrine.orm.proxiesCacheDir'];
     /** @var string $repositoriesCacheDir */
     $repositoriesCacheDir = $container['doctrine.orm.repositoriesCacheDir'];
     /** @var LoggerInterface $logger */
     $logger = $container['doctrine.orm.logger'];
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($entitiesCacheDir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
     /** @var \SplFileInfo $file */
     foreach ($iterator as $file) {
         if ($file->isDir()) {
             rmdir($file);
         } else {
             unlink($file);
         }
     }
     /** @var EntityManager $entityManager */
     $entityManager = $container['doctrine.orm.entityManager'];
     // load "disconnected" metadata (without reflection class) information
     $classMetadataFactory = new DisconnectedClassMetadataFactory();
     $classMetadataFactory->setEntityManager($entityManager);
     $metadatas = $classMetadataFactory->getAllMetadata();
     if (count($metadatas)) {
         $generated = array();
         // Create EntityGenerator
         /** @var EntityGenerator $entityGenerator */
         $entityGenerator = $container['doctrine.orm.entityGeneratorFactory'](true);
         foreach ($metadatas as $metadata) {
             static::generateEntity($metadata, $entitiesCacheDir, $entityGenerator, $output);
             $generated[] = $metadata->name;
         }
         if ($output) {
             $output->write(PHP_EOL . sprintf('Entity classes generated to "<info>%s</info>"', $entitiesCacheDir) . PHP_EOL);
         }
         $logger->info(sprintf('Entity classes generated to "%s"', $entitiesCacheDir));
         // (re)load "connected" metadata information
         $classMetadataFactory = $entityManager->getMetadataFactory();
         try {
             $metadatas = $classMetadataFactory->getAllMetadata();
             $entityManager->getProxyFactory()->generateProxyClasses($metadatas, $proxiesCacheDir);
             if ($output) {
                 $output->write(PHP_EOL . sprintf('Entity proxies generated to "<info>%s</info>"', $proxiesCacheDir) . PHP_EOL);
             }
             $logger->info(sprintf('Entity proxies generated to "%s"', $proxiesCacheDir));
             $repositoryGenerator = new EntityRepositoryGenerator();
             foreach ($metadatas as $metadata) {
                 if ($metadata->customRepositoryClassName) {
                     if ($output) {
                         $output->write(sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName) . PHP_EOL);
                     }
                     $repositoryGenerator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $repositoriesCacheDir);
                 }
             }
         } catch (\ReflectionException $e) {
             // silently ignore and reload
             $reload = true;
         }
         if ($output) {
             $output->write(PHP_EOL . sprintf('Entity repositories generated to "<info>%s</info>"', $repositoriesCacheDir) . PHP_EOL);
         }
         $logger->info(sprintf('Entity repositories generated to "%s"', $repositoriesCacheDir));
         return $generated;
     } else {
         return false;
     }
 }
コード例 #11
0
 /**
  * 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);
     }
     $metadatas = $em->getMetadataFactory()->getAllMetadata();
     if (!empty($this->filter)) {
         $metadatas = MetadataFilter::filter($metadatas, $this->filter);
     }
     if (count($metadatas)) {
         $numRepositories = 0;
         $generator = new EntityRepositoryGenerator();
         foreach ($metadatas as $metadata) {
             if ($metadata->customRepositoryClassName) {
                 $this->log(sprintf('Processing entity %s', $metadata->name));
                 $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $this->output);
                 $numRepositories++;
             }
         }
         if ($numRepositories) {
             // Outputting information message
             $this->log(sprintf('Repository classes generated to %s', $this->output));
         } else {
             $this->log('No repository classes were found to be processed');
         }
     } else {
         $this->log('No metadata classes to process');
     }
 }
コード例 #12
0
ファイル: Store.php プロジェクト: williamamed/Raptor2
 /**
  * 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));
 }
コード例 #13
0
 /**
  * @param string $className
  * @param string $defaultRepository
  * @return string
  */
 private function writeRepositoryClass($className, $defaultRepository = null)
 {
     $this->_repositoryGenerator->setDefaultRepositoryName($defaultRepository);
     $this->_repositoryGenerator->writeEntityRepositoryClass($className . 'Repository', $this->_tmpDir);
     return $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . 'Repository.php';
 }
コード例 #14
0
 /**
  * Generate repository classes
  *
  * @param array $metadata            
  */
 protected function generateRepositories(array $metadata)
 {
     $generator = new EntityRepositoryGenerator();
     /* @var $classMetadata \Doctrine\ORM\Mapping\ClassMetadata */
     foreach ($metadata as $classMetadata) {
         $className = str_replace($this->getNsEntity(), $this->getNsRepository(), $classMetadata->getName());
         $generator->writeEntityRepositoryClass($className, $this->getDirectory());
     }
 }