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('Clearing 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('Fixing entity "<info>%s</info>"', $name));
             $metadata = $manager->getClassMetadata($name, $input->getOption('path'));
         } else {
             $output->writeln(sprintf('Fixing entities for namespace "<info>%s</info>"', $name));
             $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path'));
         }
     }
     foreach ($metadata->getMetadata() as $m) {
         // 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('  > fixing <comment>%s</comment>', $m->name));
         $res = $this->fixEntity($m, $entityMetadata->getPath());
         if (!$res) {
             $output->writeln(sprintf('> FAILED'));
         }
     }
 }
Esempio n. 2
0
 protected function createForOrm(BundleInterface $bundle, $entities, CrudGenerator $generator, OutputInterface $output)
 {
     $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     $metadata = $manager->getBundleMetadata($bundle);
     $generator->openFile();
     /** @var ClassMetadata $m */
     foreach ($metadata->getMetadata() as $m) {
         try {
             $entityMetadata = $manager->getClassMetadata($m->getName());
         } catch (\RuntimeException $e) {
             $entityMetadata = $metadata;
         }
         $name = str_replace($entityMetadata->getNamespace() . '\\', '', $m->name);
         if (0 < count($entities) && !in_array($name, $entities)) {
             continue;
         }
         $output->writeln(sprintf('  > generating <comment>%s</comment>', $m->name));
         $properties = [];
         /** @var  $column */
         foreach ($m->getReflectionProperties() as $key => $column) {
             if ($key !== 'id') {
                 $properties[] = $key;
             }
         }
         $generator->generate($name, $entityMetadata->getNamespace(), $properties);
         $generator->register($name, $entityMetadata->getNamespace());
     }
     $generator->closeFile();
 }
 protected function getMetadata(InputInterface $input, OutputInterface $output, $displayStatus)
 {
     $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     try {
         $bundle = $this->getContainer()->get("kernel")->getBundle($input->getArgument('name'));
         if ($displayStatus) {
             $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)) {
             if ($displayStatus) {
                 $output->writeln(sprintf('Generating entity "<info>%s</info>"', $name));
             }
             $metadata = $manager->getClassMetadata($name, $input->getOption('path'));
         } else {
             if ($displayStatus) {
                 $output->writeln(sprintf('Generating entities for namespace "<info>%s</info>"', $name));
             }
             $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path'));
         }
     }
     return $metadata;
 }
 public function testFindNamespaceAndPathForMetadata()
 {
     $class = new ClassMetadataInfo(__CLASS__);
     $collection = new ClassMetadataCollection(array($class));
     $registry = $this->getMock('Doctrine\\Common\\Persistence\\ManagerRegistry');
     $factory = new DisconnectedMetadataFactory($registry);
     $this->setExpectedException("RuntimeException", "Can't find base path for \"Doctrine\\Bundle\\DoctrineBundle\\Tests\\Mapping\\DisconnectedMetadataFactoryTest");
     $factory->findNamespaceAndPathForMetadata($collection);
 }
 public function testFindNamespaceAndPathForMetadata()
 {
     $class = new ClassMetadataInfo('\\Vendor\\Package\\Class');
     $collection = new ClassMetadataCollection(array($class));
     $registry = $this->getMock('Doctrine\\Common\\Persistence\\ManagerRegistry');
     $factory = new DisconnectedMetadataFactory($registry);
     $factory->findNamespaceAndPathForMetadata($collection, '/path/to/code');
     $this->assertEquals('\\Vendor\\Package', $collection->getNamespace());
 }
 /**
  * {@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 getEntityMetadata($entity)
 {
     $factory = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     return $factory->getClassMetadata($entity)->getMetadata();
 }
    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);
                    }
                }
            }
        }
    }
 /**
  * Generates the show.html.twig template in the final bundle.
  *
  * @param string $dir The path to the folder that hosts templates in the bundle
  */
 private function generateShowView($dir)
 {
     //-------- CPANA -----------------------------------------
     $entity_assoc = NULL;
     // is the name of the property holding objects from the associatied class ( and not the name of the actual assoc. class)
     $fields_assoc = NULL;
     $entity_assoc_class = NULL;
     //the name of the associated class
     $keys = array();
     //--- verify if there is any property representing an association (one-to-many bidirectional etc)
     if (!empty(array_keys($this->metadata->associationMappings))) {
         $assoc = $this->metadata->associationMappings;
         foreach ($assoc as $key => $value) {
             if ($assoc[$key]['isOwningSide'] == 0) {
                 $keys[] = $assoc[$key]['fieldName'];
                 $entity_assoc_class = $assoc[$key]['targetEntity'];
             }
         }
         if (!empty($keys)) {
             //it is possible that the entity has association but if are owning sides we do not want to add them, so is possible that the
             $entity_assoc = $keys[0];
             // array keys[] to be empty
             global $kernel;
             //$entityClass = 'AppBundle\\Entity\\'.$entity_assoc;
             $factory = new DisconnectedMetadataFactory($kernel->getContainer()->get('doctrine'));
             $metadata_assoc = $factory->getClassMetadata($entity_assoc_class)->getMetadata();
             $fields_assoc = $metadata_assoc[0]->fieldMappings;
         }
     }
     //---------------------------------------
     $this->renderFile('crud/views/show.html.twig.twig', $dir . '/show.html.twig', array('bundle' => $this->bundle->getName(), 'entity' => $this->entity, 'fields' => $this->metadata->fieldMappings, 'entity_assoc' => $entity_assoc, 'fields_assoc' => $fields_assoc, 'entity_assoc_class' => $entity_assoc_class, 'actions' => $this->actions, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, 'layout' => $this->layout, 'bodyBlock' => $this->bodyBlock));
 }
 protected function getConfigEntityName($input, $output)
 {
     $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     try {
         $configBundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('configBundle'));
         $configBundleMetadata = $manager->getBundleMetadata($configBundle);
         $configMetadata = $configBundleMetadata->getMetadata();
         $configEntityName = $configMetadata[0]->getName();
     } catch (\InvalidArgumentException $e) {
         try {
             $configModel = $this->getContainer()->get("model_factory")->getModel($input->getArgument('configBundle'));
             $configMetadata = $configModel->getMetadata();
             $configEntityName = $configMetadata->getName();
         } catch (\Exception $e) {
             $output->writeln("<error>Argument configBundle:\"" . $input->getArgument('configBundle') . "\" not exist.</error>");
             exit;
         }
     }
     if (!$configEntityName) {
         $output->writeln("<error>Argument configEntityName not exist.</error>");
         exit;
     }
     return $configEntityName;
 }
 /**
  * Sets the variables holding information about associated entities in bidirectional relations.
  *
  * @author Cristian Pana
  */
 protected function getAssociatedEntities()
 {
     $keys = array();
     //--- verify if there is any property representing an association (one-to-many bidirectional etc)
     if (!empty(array_keys($this->metadata->associationMappings))) {
         $assoc = $this->metadata->associationMappings;
         foreach ($assoc as $key => $value) {
             if (0 == $assoc[$key]['isOwningSide']) {
                 $keys[] = $assoc[$key]['fieldName'];
                 $this->entityAssocClassName[$assoc[$key]['fieldName']] = $assoc[$key]['targetEntity'];
             }
         }
         if (!empty($keys)) {
             //it is possible that the entity has association but if they are owning sides we do not want to add them,
             $this->entityAssocProperty = (array) $keys;
             global $kernel;
             $factory = new DisconnectedMetadataFactory($kernel->getContainer()->get('doctrine'));
             foreach ($this->entityAssocClassName as $fieldName => $className) {
                 //$metadata_assoc = $factory->getClassMetadata($this->entityAssocClassName[$value])->getMetadata();
                 $metadata_assoc = $factory->getClassMetadata($className)->getMetadata();
                 $this->fieldsOfAssocEntity[$fieldName] = $metadata_assoc[0]->fieldMappings;
             }
         }
     }
 }
 protected function getClassPath()
 {
     $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     $classPath = $manager->getClassMetadata($this->getEntityName())->getPath();
     return $classPath;
 }
 protected function getBundleMetadata(BundleInterface $bundle)
 {
     $factory = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
     return $factory->getBundleMetadata($bundle)->getMetadata();
 }