Completed
Pull Request — master (#791)
by
unknown
02:17
created

ImportMappingDoctrineCommand   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
c 1
b 0
f 0
lcom 2
cbo 12
dl 0
loc 127
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B configure() 0 42 1
D execute() 0 75 12
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Command;
4
5
use Doctrine\ORM\Mapping\Driver\DatabaseDriver;
6
use Doctrine\ORM\Tools\Console\MetadataFilter;
7
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
8
use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
9
use Symfony\Component\Console\Input\InputArgument;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
/**
15
 * Import Doctrine ORM metadata mapping information from an existing database.
16
 */
17
class ImportMappingDoctrineCommand extends DoctrineCommand
18
{
19
    /**
20
     * {@inheritDoc}
21
     */
22
    protected function configure()
23
    {
24
        $this
25
            ->setName('doctrine:mapping:import')
26
            ->addArgument('name', InputArgument::REQUIRED, 'The bundle or namespace to import the mapping information to')
27
            ->addArgument('mapping-type', InputArgument::OPTIONAL, 'The mapping type to export the imported mapping information to')
28
            ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command')
29
            ->addOption('shard', null, InputOption::VALUE_REQUIRED, 'The shard connection to use for this command')
30
            ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be mapped.')
31
            ->addOption('force', null, InputOption::VALUE_NONE, 'Force to overwrite existing mapping files.')
32
            ->addOption('path', null, InputOption::VALUE_REQUIRED, 'The path where the files would be generated (not used when a bundle is passed).')
33
            ->setDescription('Imports mapping information from an existing database')
34
            ->setHelp(<<<EOT
35
The <info>%command.name%</info> command imports mapping information
36
from an existing database:
37
38
Generate annotation mappings into the src/ directory using App as the namespace:
39
<info>php %command.full_name% App\\\Entity annotation --path=src/Entity</info>
40
41
Generate annotation mappings into the config/doctrine/ directory using App as the namespace:
42
<info>php %command.full_name% App\\\Entity xml --path=config/doctrine</info>
43
44
Generate XML mappings into a bundle:
45
<info>php %command.full_name% "MyCustomBundle" xml</info>
46
47
You can also optionally specify which entity manager to import from with the
48
<info>--em</info> option:
49
50
<info>php %command.full_name% "MyCustomBundle" xml --em=default</info>
51
52
If you don't want to map every entity that can be found in the database, use the
53
<info>--filter</info> option. It will try to match the targeted mapped entity with the
54
provided pattern string.
55
56
<info>php %command.full_name% "MyCustomBundle" xml --filter=MyMatchedEntity</info>
57
58
Use the <info>--force</info> option, if you want to override existing mapping files:
59
60
<info>php %command.full_name% "MyCustomBundle" xml --force</info>
61
EOT
62
        );
63
    }
64
65
    /**
66
     * {@inheritDoc}
67
     */
68
    protected function execute(InputInterface $input, OutputInterface $output)
69
    {
70
        $type     = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
71
        if ($type === 'yaml') {
72
            $type = 'yml';
73
        }
74
75
        $bundles = $this->getContainer()->getParameter('kernel.bundles');
76
        if (isset($bundles[$input->getArgument('name')])) {
77
            $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name'));
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
78
            $namespace = $bundle->getNamespace(). '\\Entity';
79
80
            $destPath = $bundle->getPath();
81
            if ($type === 'annotation') {
82
                $destPath .= '/Entity';
83
            } else {
84
                $destPath .= '/Resources/config/doctrine';
85
            }
86
        } else {
87
            // assume a namespace has been passed
88
            $namespace = $input->getArgument('name');
89
            if (null === $destPath = $input->getOption('path')) {
90
                throw new \InvalidArgumentException('The --path option is required when passing a namespace (e.g. --path=src). If you intended to pass a bundle name, check your spelling.');
91
            }
92
        }
93
94
        $cme      = new ClassMetadataExporter();
95
        $exporter = $cme->getExporter($type);
96
        $exporter->setOverwriteExistingFiles($input->getOption('force'));
97
98
        if ($type === 'annotation') {
99
            $entityGenerator = $this->getEntityGenerator();
100
            $exporter->setEntityGenerator($entityGenerator);
101
        }
102
103
        $em = $this->getEntityManager($input->getOption('em'), $input->getOption('shard'));
104
105
        $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
106
        $em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
107
108
        $emName = $input->getOption('em');
109
        $emName = $emName ? $emName : 'default';
110
111
        $cmf = new DisconnectedClassMetadataFactory();
112
        $cmf->setEntityManager($em);
113
        $metadata = $cmf->getAllMetadata();
114
        $metadata = MetadataFilter::filter($metadata, $input->getOption('filter'));
115
        if ($metadata) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $metadata of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
116
            $output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', $emName));
117
            foreach ($metadata as $class) {
118
                $className   = $class->name;
119
                $class->name = $namespace . '\\' . $className;
120
                if ($type === 'annotation') {
121
                    $path = $destPath . '/' . str_replace('\\', '.', $className) . '.php';
122
                } else {
123
                    $path = $destPath . '/' . str_replace('\\', '.', $className) . '.orm.' . $type;
124
                }
125
                $output->writeln(sprintf('  > writing <comment>%s</comment>', $path));
126
                $code = $exporter->exportClassMetadata($class);
127
                $dir  = dirname($path);
128
                if (! is_dir($dir)) {
129
                    mkdir($dir, 0775, true);
130
                }
131
                file_put_contents($path, $code);
132
                chmod($path, 0664);
133
            }
134
135
            return 0;
136
        } else {
137
            $output->writeln('Database does not have any mapping information.');
138
            $output->writeln('');
139
140
            return 1;
141
        }
142
    }
143
}
144