CreateDatabaseDoctrineCommand::execute()   F
last analyzed

Complexity

Conditions 15
Paths 3280

Size

Total Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 69
rs 1.7499
cc 15
nc 3280
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Command;
4
5
use Doctrine\DBAL\DriverManager;
6
use Exception;
7
use InvalidArgumentException;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
/**
13
 * Database tool allows you to easily create your configured databases.
14
 *
15
 * @final
16
 */
17
class CreateDatabaseDoctrineCommand extends DoctrineCommand
18
{
19
    /**
20
     * {@inheritDoc}
21
     */
22
    protected function configure()
23
    {
24
        $this
25
            ->setName('doctrine:database:create')
26
            ->setDescription('Creates the configured database')
27
            ->addOption('shard', 's', InputOption::VALUE_REQUIRED, 'The shard connection to use for this command')
28
            ->addOption('connection', 'c', InputOption::VALUE_OPTIONAL, 'The connection to use for this command')
29
            ->addOption('if-not-exists', null, InputOption::VALUE_NONE, 'Don\'t trigger an error, when the database already exists')
30
            ->setHelp(<<<EOT
31
The <info>%command.name%</info> command creates the default connections database:
32
33
    <info>php %command.full_name%</info>
34
35
You can also optionally specify the name of a connection to create the database for:
36
37
    <info>php %command.full_name% --connection=default</info>
38
EOT
39
        );
40
    }
41
42
    /**
43
     * {@inheritDoc}
44
     */
45
    protected function execute(InputInterface $input, OutputInterface $output)
46
    {
47
        $connectionName = $input->getOption('connection');
48
        if (empty($connectionName)) {
49
            $connectionName = $this->getDoctrine()->getDefaultConnectionName();
50
        }
51
        $connection = $this->getDoctrineConnection($connectionName);
52
53
        $ifNotExists = $input->getOption('if-not-exists');
54
55
        $params = $connection->getParams();
56
        if (isset($params['master'])) {
57
            $params = $params['master'];
58
        }
59
60
        // Cannot inject `shard` option in parent::getDoctrineConnection
61
        // cause it will try to connect to a non-existing database
62
        if (isset($params['shards'])) {
63
            $shards = $params['shards'];
64
            // Default select global
65
            $params = array_merge($params, $params['global']);
66
            unset($params['global']['dbname'], $params['global']['path'], $params['global']['url']);
67
            if ($input->getOption('shard')) {
68
                foreach ($shards as $i => $shard) {
69
                    if ($shard['id'] === (int) $input->getOption('shard')) {
70
                        // Select sharded database
71
                        $params = array_merge($params, $shard);
72
                        unset($params['shards'][$i]['dbname'], $params['shards'][$i]['path'], $params['shards'][$i]['url'], $params['id']);
73
                        break;
74
                    }
75
                }
76
            }
77
        }
78
79
        $hasPath = isset($params['path']);
80
        $name    = $hasPath ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
81
        if (! $name) {
82
            throw new InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be created.");
83
        }
84
        // Need to get rid of _every_ occurrence of dbname from connection configuration and we have already extracted all relevant info from url
85
        unset($params['dbname'], $params['path'], $params['url']);
86
87
        $tmpConnection = DriverManager::getConnection($params);
88
        $tmpConnection->connect($input->getOption('shard'));
0 ignored issues
show
Unused Code introduced by
The call to Connection::connect() has too many arguments starting with $input->getOption('shard').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
89
        $shouldNotCreateDatabase = $ifNotExists && in_array($name, $tmpConnection->getSchemaManager()->listDatabases());
90
91
        // Only quote if we don't have a path
92
        if (! $hasPath) {
93
            $name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
94
        }
95
96
        $error = false;
97
        try {
98
            if ($shouldNotCreateDatabase) {
99
                $output->writeln(sprintf('<info>Database <comment>%s</comment> for connection named <comment>%s</comment> already exists. Skipped.</info>', $name, $connectionName));
100
            } else {
101
                $tmpConnection->getSchemaManager()->createDatabase($name);
102
                $output->writeln(sprintf('<info>Created database <comment>%s</comment> for connection named <comment>%s</comment></info>', $name, $connectionName));
103
            }
104
        } catch (Exception $e) {
105
            $output->writeln(sprintf('<error>Could not create database <comment>%s</comment> for connection named <comment>%s</comment></error>', $name, $connectionName));
106
            $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
107
            $error = true;
108
        }
109
110
        $tmpConnection->close();
111
112
        return $error ? 1 : 0;
113
    }
114
}
115