فهرست منبع

[DoctrineBundle] More cleanups of doctrine commands.

Benjamin Eberlei 14 سال پیش
والد
کامیت
5014ee9739

+ 1 - 1
src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php

@@ -49,7 +49,7 @@ EOT
 
     protected function execute(InputInterface $input, OutputInterface $output)
     {
-        $connection = $this->getDoctrineConnection($intput->getOption('connection'));
+        $connection = $this->getDoctrineConnection($input->getOption('connection'));
         
         $params = $connection->getParams();
         $name = isset($params['path']) ? $params['path']:$params['dbname'];

+ 36 - 0
src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php

@@ -134,4 +134,40 @@ abstract class DoctrineCommand extends Command
 
         return $bundleMetadatas;
     }
+
+    protected function findBundle($bundleName)
+    {
+        $foundBundle = false;
+        foreach ($this->application->getKernel()->getBundles() as $bundle) {
+            /* @var $bundle Bundle */
+            if (strtolower($bundleName) == strtolower($bundle->getName())) {
+                $foundBundle = $bundle;
+                break;
+            }
+        }
+
+        if (!$foundBundle) {
+            throw new \InvalidArgumentException("No bundle " . $bundleName . " was found.");
+        }
+
+        return $foundBundle;
+    }
+
+    /**
+     * Transform classname to a path $foundBundle substract it to get the destination
+     *
+     * @param Bundle $bundle
+     * @return string
+     */
+    protected function findBasePathForBundle($bundle)
+    {
+        $path = str_replace('\\', '/', $bundle->getNamespace());
+        $destination = str_replace('/'.$path, "", $bundle->getPath(), $c);
+
+        if ($c != 1) {
+            throw new \RuntimeException("Something went terribly wrong.");
+        }
+
+        return $destination;
+    }
 }

+ 1 - 1
src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php

@@ -54,7 +54,7 @@ EOT
 
     protected function execute(InputInterface $input, OutputInterface $output)
     {
-        $connection = $this->getDoctrineConnection($intput->getOption('connection'));
+        $connection = $this->getDoctrineConnection($input->getOption('connection'));
         
         $params = $connection->getParams();
 

+ 19 - 20
src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php

@@ -16,8 +16,6 @@ use Symfony\Component\Console\Input\InputOption;
 use Symfony\Component\Console\Input\InputInterface;
 use Symfony\Component\Console\Output\OutputInterface;
 use Symfony\Component\Console\Output\Output;
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-use Doctrine\ORM\Tools\EntityGenerator;
 
 /**
  * Generate entity classes from mapping information
@@ -32,7 +30,7 @@ class GenerateEntitiesDoctrineCommand extends DoctrineCommand
         $this
             ->setName('doctrine:generate:entities')
             ->setDescription('Generate entity classes and method stubs from your mapping information.')
-            ->addOption('bundle', null, InputOption::VALUE_REQUIRED, 'The bundle to initialize the entity or entities in.')
+            ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the entity or entities in.')
             ->addOption('entity', null, InputOption::VALUE_OPTIONAL, 'The entity class to initialize (shortname without namespace).')
             ->setHelp(<<<EOT
 The <info>doctrine:generate:entities</info> command generates entity classes and method stubs from your mapping information:
@@ -52,30 +50,31 @@ EOT
 
     protected function execute(InputInterface $input, OutputInterface $output)
     {
+        $bundleName = $input->getArgument('bundle');
         $filterEntity = $input->getOption('entity');
 
-        $entityGenerator = $this->getEntityGenerator();
-        foreach ($this->application->getKernel()->getBundles() as $bundle) {
-            /* @var $bundle Bundle */
-            if ($input->getOption('bundle') != $bundle->getName()) {
-                continue;
-            }
+        $foundBundle = $this->findBundle($bundleName);
 
-            // transform classname to a path and substract it to get the destination
-            $path = dirname(str_replace('\\', '/', $bundle->getNamespace()));
-            $destination = str_replace('/'.$path, "", $bundle->getPath());
+        if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
+            $output->writeln(sprintf('Generating entities for "<info>%s</info>"', $foundBundle->getName()));
+            $entityGenerator = $this->getEntityGenerator();
 
-            if ($metadatas = $this->getBundleMetadatas($bundle)) {
-                $output->writeln(sprintf('Generating entities for "<info>%s</info>"', $class));
+            foreach ($metadatas as $metadata) {
+                if ($filterEntity && $metadata->reflClass->getShortName() == $filterEntity) {
+                    continue;
+                }
 
-                foreach ($metadatas as $metadata) {
-                    if ($filterEntity && $metadata->reflClass->getShortName() == $filterEntity) {
-                        continue;
-                    }
-                    $output->writeln(sprintf('  > generating <comment>%s</comment>', $metadata->name));
-                    $entityGenerator->generate(array($metadata), $destination);
+                if (strpos($metadata->name, $foundBundle->getNamespace()) === false) {
+                    throw new \RuntimeException(
+                        "Entity " . $metadata->name . " and bundle don't have a commont namespace, ".
+                        "generation failed because the target directory cannot be detected.");
                 }
+
+                $output->writeln(sprintf('  > generating <comment>%s</comment>', $metadata->name));
+                $entityGenerator->generate(array($metadata), $this->findBasePathForBundle($foundBundle));
             }
+        } else {
+            throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped entities.");
         }
     }
 }

+ 40 - 16
src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntityDoctrineCommand.php

@@ -73,15 +73,17 @@ EOT
             foreach ($e as $value) {
                 $e = explode(':', $value);
                 $name = $e[0];
-                $type = isset($e[1]) ? $e[1] : 'string';
-                preg_match_all('/(.*)\((.*)\)/', $type, $matches);
-                $type = isset($matches[1][0]) ? $matches[1][0] : $type;
-                $length = isset($matches[2][0]) ? $matches[2][0] : null;
-                $class->mapField(array(
-                    'fieldName' => $name,
-                    'type' => $type,
-                    'length' => $length
-                ));
+                if (strlen($name)) {
+                    $type = isset($e[1]) ? $e[1] : 'string';
+                    preg_match_all('/(.*)\((.*)\)/', $type, $matches);
+                    $type = isset($matches[1][0]) ? $matches[1][0] : $type;
+                    $length = isset($matches[2][0]) ? $matches[2][0] : null;
+                    $class->mapField(array(
+                        'fieldName' => $name,
+                        'type' => $type,
+                        'length' => $length
+                    ));
+                }
             }
         }
 
@@ -89,22 +91,44 @@ EOT
         $cme = new ClassMetadataExporter();
         $exporter = $cme->getExporter($mappingType);
 
+        $entityPath = $bundle->getPath().'/Entity/'.$entity.'.php';
+        if (file_exists($entityPath)) {
+            throw new \RuntimeException(sprintf("Entity %s already exists.", $class->name));
+        }
+
         if ('annotation' === $mappingType) {
-            $path = $bundle->getPath().'/Entity/'.$entity.'.php';
             $exporter->setEntityGenerator($this->getEntityGenerator());
+            $entityCode = $exporter->exportClassMetadata($class);
+            $mappingPath = $mappingCode = false;
         } else {
             $mappingType = 'yaml' == $mappingType ? 'yml' : $mappingType;
-            $path = $bundle->getPath().'/Resources/config/doctrine/metadata/orm/'.str_replace('\\', '.', $fullEntityClassName).'.dcm.'.$mappingType;
-        }
+            $mappingPath = $bundle->getPath().'/Resources/config/doctrine/metadata/orm/'.str_replace('\\', '.', $fullEntityClassName).'.dcm.'.$mappingType;
+            $mappingCode = $exporter->exportClassMetadata($class);
 
-        $code = $exporter->exportClassMetadata($class);
+            $entityGenerator = $this->getEntityGenerator();
+            $entityCode = $entityGenerator->generateEntityClass($class);
+
+            if (file_exists($mappingPath)) {
+                throw new \RuntimeException(sprintf("Cannot generate entity when mapping <info>%s</info> already exists", $mappingPath));
+            }
+        }
 
         $output->writeln(sprintf('Generating entity for "<info>%s</info>"', $bundle->getName()));
-        $output->writeln(sprintf('  > generating <comment>%s</comment>', $fullEntityClassName));
+        $output->writeln(sprintf('  > entity <comment>%s</comment> into <info>%s</info>', $fullEntityClassName, $entityPath));
 
-        if (!is_dir($dir = dirname($path))) {
+        if (!is_dir($dir = dirname($entityPath))) {
             mkdir($dir, 0777, true);
         }
-        file_put_contents($path, $code);
+        file_put_contents($entityPath, $entityCode);
+
+        if ($mappingPath) {
+            $output->writeln(sprintf('  > mapping into <info>%s</info>', $mappingPath));
+
+            if (!is_dir($dir = dirname($mappingPath))) {
+                mkdir($dir, 0777, true);
+            }
+            file_put_contents($mappingPath, $mappingCode);
+        }
+
     }
 }

+ 30 - 9
src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php

@@ -11,9 +11,11 @@
 
 namespace Symfony\Bundle\DoctrineBundle\Command;
 
+use Symfony\Component\Console\Input\InputArgument;
 use Symfony\Component\Console\Input\InputOption;
 use Symfony\Component\Console\Input\InputInterface;
 use Symfony\Component\Console\Output\OutputInterface;
+use Symfony\Component\Console\Output\Output;
 use Doctrine\ORM\Tools\EntityRepositoryGenerator;
 
 /**
@@ -29,6 +31,8 @@ class GenerateRepositoriesDoctrineCommand extends DoctrineCommand
         $this
             ->setName('doctrine:generate:repositories')
             ->setDescription('Generate repository classes from your mapping information.')
+            ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the repositories in.')
+            ->addOption('entity', null, InputOption::VALUE_OPTIONAL, 'The entity class to generate the repository for (shortname without namespace).')
             ->setHelp(<<<EOT
 The <info>doctrine:generate:repositories</info> command generates the configured entity repository classes from your mapping information:
 
@@ -39,18 +43,35 @@ EOT
 
     protected function execute(InputInterface $input, OutputInterface $output)
     {
-        $generator = new EntityRepositoryGenerator();
-        foreach ($this->application->getKernel()->getBundles() as $bundle) {
-            $destination = $bundle->getPath();
-            if ($metadatas = $this->getBundleMetadatas($bundle)) {
-                $output->writeln(sprintf('Generating entity repositories for "<info>%s</info>"', get_class($bundle)));
-                foreach ($metadatas as $metadata) {
-                    if ($metadata->customRepositoryClassName) {
-                        $output->writeln(sprintf('  > generating <comment>%s</comment>', $metadata->customRepositoryClassName));
-                        $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destination);
+        $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->getName()) === false) {
+                        throw new \RuntimeException(
+                            "Repository " . $metadata->customRepositoryClassName . " and bundle don't have a commont 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.");
         }
     }
 }