GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Fastdump::execute()   F
last analyzed

Complexity

Conditions 20
Paths 2568

Size

Total Lines 91
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 420

Importance

Changes 0
Metric Value
cc 20
eloc 59
nc 2568
nop 2
dl 0
loc 91
ccs 0
cts 76
cp 0
crap 420
rs 0
c 0
b 0
f 0

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 Graze\Morphism\Command;
4
5
use Exception;
6
use Graze\Morphism\Parse\TokenStream;
7
use Graze\Morphism\Parse\MysqlDump;
8
use Graze\Morphism\Extractor;
9
use Graze\Morphism\Config;
10
use RuntimeException;
11
use Symfony\Component\Console\Command\Command;
12
use Symfony\Component\Console\Input\InputArgument;
13
use Symfony\Component\Console\Input\InputInterface;
14
use Symfony\Component\Console\Output\OutputInterface;
15
16
class Fastdump extends Command
17
{
18
    const COMMAND_NAME          = 'dump';
19
20
    // Command line arguments
21
    const ARGUMENT_CONFIG_FILE  = 'config-file';
22
    const ARGUMENT_CONNECTIONS  = 'connections';
23
24
    // Command line options
25
    const OPTION_QUOTE_NAMES    = 'quote-names';
26
    const OPTION_NO_QUOTE_NAMES = 'no-quote-names';
27
    const OPTION_WRITE          = 'write';
28
    const OPTION_NO_WRITE       = 'no-write';
29
30
    /** @var bool */
31
    private $quoteNames = true;
32
    /** @var string|null */
33
    private $configFile = null;
34
    /** @var bool */
35
    private $write = false;
36
    /** @var array */
37
    private $connectionNames = [];
38
39
    protected function configure()
40
    {
41
        $this->setName(self::COMMAND_NAME);
42
43
        $helpText = sprintf(
44
            "Usage: %s [OPTIONS] CONFIG-FILE [CONN ...]\n" .
45
            "Dumps database schemas for named connections. This tool is considerably faster\n" .
46
            "than mysqldump, especially for large schemas. You might use this tool to\n" .
47
            "(re-)initalise your project's schema directory from a local database.\n" .
48
            "If no connections are specified, all connections\n" .
49
            "in the config with 'morphism: enable: true' will be used.\n" .
50
            "\n" .
51
            "OPTIONS\n" .
52
            "  -h, -help, --help   display this message, and exit\n" .
53
            "  --[no-]quote-names  [do not] quote names with `...`; default: yes\n" .
54
            "  --[no-]write        write schema files to schema path; default: no\n" .
55
            "\n" .
56
            "CONFIG-FILE\n" .
57
            "A YAML file mapping connection names to parameters. See the morphism project's\n" .
58
            "README.md file for detailed information.\n" .
59
            "",
60
            self::COMMAND_NAME
61
        );
62
        $this->setHelp($helpText);
63
64
        $this->setDescription("Dump database schema for a named database connection");
65
66
        $this->addArgument(
67
            self::ARGUMENT_CONFIG_FILE,
68
            InputArgument::REQUIRED
69
        );
70
71
        $this->addArgument(
72
            self::ARGUMENT_CONNECTIONS,
73
            InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
74
            '',
75
            []
76
        );
77
78
        $this->addOption(self::OPTION_QUOTE_NAMES);
79
        $this->addOption(self::OPTION_NO_QUOTE_NAMES);
80
81
        $this->addOption(self::OPTION_WRITE);
82
        $this->addOption(self::OPTION_NO_WRITE);
83
    }
84
85
    /**
86
     * @param InputInterface $input
87
     * @param OutputInterface $output
88
     * @throws Exception
89
     */
90
    protected function execute(InputInterface $input, OutputInterface $output)
91
    {
92
        $this->configFile = $input->getArgument(self::ARGUMENT_CONFIG_FILE);
93
        $this->connectionNames = $input->getArgument(self::ARGUMENT_CONNECTIONS);
94
95
        if ($input->getOption(self::OPTION_QUOTE_NAMES)) {
96
            $this->quoteNames = false;
97
        }
98
99
        if ($input->getOption(self::OPTION_WRITE)) {
100
            $this->write = true;
101
        }
102
103
        $config = new Config($this->configFile);
104
        $config->parse();
105
106
        if (!$this->connectionNames) {
107
            $this->connectionNames = $config->getConnectionNames();
108
        }
109
110
        foreach ($this->connectionNames as $connectionName) {
111
            $connection = $config->getConnection($connectionName);
112
113
            $entry = $config->getEntry($connectionName);
114
            $dbName = $entry['connection']['dbname'];
115
            $matchTables = $entry['morphism']['matchTables'];
116
            $schemaDefinitionPaths = $entry['morphism']['schemaDefinitionPath'];
117
118
            if (!$this->write) {
119
                $output->writeln('<info>');
120
                $output->writeln("/********* Connection: $connectionName Database: $dbName *********/");
121
                $output->writeln('</info>');
122
            }
123
124
            $extractor = new Extractor($connection);
125
            $extractor->setDatabases([$dbName]);
126
            $extractor->setCreateDatabases(false);
127
            $extractor->setQuoteNames($this->quoteNames);
128
            $text = '';
129
            foreach ($extractor->extract() as $query) {
130
                $text .= "$query;\n";
131
            }
132
            $stream = TokenStream::newFromText($text, '');
133
134
            $dump = new MysqlDump();
135
            try {
136
                $dump->parse($stream, ['matchTables' => $matchTables]);
137
            } catch (RuntimeException $e) {
138
                throw new RuntimeException($stream->contextualise($e->getMessage()));
139
            } catch (Exception $e) {
140
                throw new Exception($e->getMessage() . "\n\n" . $e->getTraceAsString());
141
            }
142
143
            if ($this->write) {
144
                // Ensure the schema directories to write to exist
145
                foreach ($schemaDefinitionPaths as $schemaPath) {
146
                    if (!is_dir($schemaPath)) {
147
                        if (!@mkdir($schemaPath, 0755, true)) {
148
                            throw new RuntimeException("Could not make directory $schemaPath");
149
                        }
150
                    }
151
                }
152
                $database = reset($dump->databases);
153
                foreach ($database->tables as $table) {
154
                    // Find any existing schema file. If it doesn't exist, use the first schema path.
155
                    $path = null;
156
157
                    foreach ($schemaDefinitionPaths as $schemaPath) {
158
                        $possiblePath = sprintf('%s/%s.sql', $schemaPath, $table->getName());
159
                        if (file_exists($possiblePath)) {
160
                            $path = $possiblePath;
161
                            break;
162
                        }
163
                    }
164
165
                    if (!$path) {
166
                        $path = sprintf('%s/%s.sql', $schemaDefinitionPaths[0], $table->getName());
167
                    }
168
169
                    $text = '';
170
                    foreach ($table->getDDL() as $query) {
171
                        $text .= "$query;\n\n";
172
                    }
173
                    if (false === @file_put_contents($path, $text)) {
174
                        throw new RuntimeException("Could not write $path");
175
                    }
176
                    fprintf(STDERR, "wrote $path\n");
177
                }
178
            } else {
179
                foreach ($dump->getDDL() as $query) {
180
                    $output->writeln("$query;\n");
181
                }
182
            }
183
        }
184
    }
185
}
186