Completed
Push — master ( ff6cbd...ce4534 )
by Sergei
13:19 queued 13:15
created

MySqlSchemaManager   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 302
Duplicated Lines 0 %

Test Coverage

Coverage 93.62%

Importance

Changes 0
Metric Value
wmc 62
eloc 161
dl 0
loc 302
ccs 132
cts 141
cp 0.9362
rs 3.44
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
B listTableDetails() 0 38 6
F _getPortableTableColumnDefinition() 0 102 31
A _getPortableTableDefinition() 0 3 1
A _getPortableSequenceDefinition() 0 3 1
B getMariaDb1027ColumnDefault() 0 23 7
B _getPortableTableForeignKeysList() 0 41 8
A _getPortableDatabaseDefinition() 0 3 1
A _getPortableViewDefinition() 0 3 1
A _getPortableTableIndexesList() 0 20 5
A _getPortableUserDefinition() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like MySqlSchemaManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MySqlSchemaManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
6
use Doctrine\DBAL\Platforms\MySqlPlatform;
7
use Doctrine\DBAL\Types\Type;
8
use const CASE_LOWER;
9
use function array_change_key_case;
10
use function array_shift;
11
use function array_values;
12
use function end;
13
use function explode;
14
use function preg_match;
15
use function preg_replace;
16
use function str_replace;
17
use function stripslashes;
18
use function strpos;
19
use function strtok;
20
use function strtolower;
21
use function trim;
22
23
/**
24
 * Schema manager for the MySql RDBMS.
25
 */
26
class MySqlSchemaManager extends AbstractSchemaManager
27
{
28
    /**
29 8
     * {@inheritdoc}
30
     */
31 8
    protected function _getPortableViewDefinition($view)
32
    {
33
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
34
    }
35
36
    /**
37 590
     * {@inheritdoc}
38
     */
39 590
    protected function _getPortableTableDefinition($table)
40
    {
41
        return array_shift($table);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    protected function _getPortableUserDefinition($user)
48
    {
49
        return [
50
            'user' => $user['User'],
51
            'password' => $user['Password'],
52
        ];
53
    }
54
55
    /**
56 302
     * {@inheritdoc}
57
     */
58 302
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
59 168
    {
60 168
        foreach ($tableIndexes as $k => $v) {
61 128
            $v = array_change_key_case($v, CASE_LOWER);
62
            if ($v['key_name'] === 'PRIMARY') {
63 112
                $v['primary'] = true;
64
            } else {
65 168
                $v['primary'] = false;
66 24
            }
67 160
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
68 24
                $v['flags'] = ['FULLTEXT'];
69
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
70 168
                $v['flags'] = ['SPATIAL'];
71
            }
72 168
            $v['length'] = $v['sub_part'] ?? null;
73
74
            $tableIndexes[$k] = $v;
75 302
        }
76
77
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    protected function _getPortableSequenceDefinition($sequence)
84
    {
85
        return end($sequence);
86
    }
87
88
    /**
89 16
     * {@inheritdoc}
90
     */
91 16
    protected function _getPortableDatabaseDefinition($database)
92
    {
93
        return $database['Database'];
94
    }
95
96
    /**
97 366
     * {@inheritdoc}
98
     */
99 366
    protected function _getPortableTableColumnDefinition($tableColumn)
100
    {
101 366
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
102 366
103 366
        $dbType = strtolower($tableColumn['type']);
104
        $dbType = strtok($dbType, '(), ');
105 366
        $length = $tableColumn['length'] ?? strtok('(), ');
106
107 366
        $fixed = null;
108 366
109
        if (! isset($tableColumn['name'])) {
110
            $tableColumn['name'] = '';
111 366
        }
112 366
113
        $scale     = null;
114 366
        $precision = null;
115
116
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
117 366
118 366
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
119 366
        if (isset($tableColumn['comment'])) {
120
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
121
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
122
        }
123 366
124 350
        switch ($dbType) {
125 48
            case 'char':
126 48
            case 'binary':
127 350
                $fixed = true;
128 350
                break;
129 342
            case 'float':
130 342
            case 'double':
131 342
            case 'real':
132 56
            case 'numeric':
133 48
            case 'decimal':
134 48
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
135 48
                    $precision = $match[1];
136
                    $scale     = $match[2];
137 56
                    $length    = null;
138 334
                }
139 24
                break;
140 24
            case 'tinytext':
141 334
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
142 24
                break;
143 24
            case 'text':
144 334
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
145 24
                break;
146 24
            case 'mediumtext':
147 334
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
148
                break;
149
            case 'tinyblob':
150 334
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
151 24
                break;
152 24
            case 'blob':
153 334
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
154 24
                break;
155 24
            case 'mediumblob':
156 334
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
157 334
                break;
158 334
            case 'tinyint':
159 334
            case 'smallint':
160 182
            case 'mediumint':
161 182
            case 'int':
162 182
            case 'integer':
163 272
            case 'bigint':
164 272
            case 'year':
165
                $length = null;
166
                break;
167 366
        }
168 90
169
        if ($this->_platform instanceof MariaDb1027Platform) {
170 276
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
171
        } else {
172
            $columnDefault = $tableColumn['default'];
173
        }
174 366
175 366
        $options = [
176 366
            'length'        => $length !== null ? (int) $length : null,
177 366
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
178 366
            'fixed'         => (bool) $fixed,
179
            'default'       => $columnDefault,
180
            'notnull'       => $tableColumn['null'] !== 'YES',
181 366
            'scale'         => null,
182 366
            'precision'     => null,
183 112
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
184
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
185
                ? $tableColumn['comment']
186
                : null,
187 366
        ];
188 48
189 48
        if ($scale !== null && $precision !== null) {
190
            $options['scale']     = (int) $scale;
191
            $options['precision'] = (int) $precision;
192 366
        }
193
194 366
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
195 168
196
        if (isset($tableColumn['collation'])) {
197
            $column->setPlatformOption('collation', $tableColumn['collation']);
198 366
        }
199
200
        return $column;
201
    }
202
203
    /**
204
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
205
     *
206
     * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
207
     *   to distinguish them from expressions (see MDEV-10134).
208
     * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
209
     *   as current_timestamp(), currdate(), currtime()
210
     * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
211
     *   null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
212
     * - \' is always stored as '' in information_schema (normalized)
213
     *
214
     * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
215
     * @link https://jira.mariadb.org/browse/MDEV-13132
216
     *
217 90
     * @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
218
     */
219 90
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
220 82
    {
221
        if ($columnDefault === 'NULL' || $columnDefault === null) {
222 20
            return null;
223 16
        }
224 16
        if ($columnDefault[0] === "'") {
225 16
            return stripslashes(
226 16
                str_replace(
227 16
                    "''",
228
                    "'",
229
                    preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
230
                )
231
            );
232 12
        }
233 8
        switch ($columnDefault) {
234 10
            case 'current_timestamp()':
235 6
                return $platform->getCurrentTimestampSQL();
236 10
            case 'curdate()':
237 6
                return $platform->getCurrentDateSQL();
238
            case 'curtime()':
239 8
                return $platform->getCurrentTimeSQL();
240
        }
241
        return $columnDefault;
242
    }
243
244
    /**
245 289
     * {@inheritdoc}
246
     */
247 289
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
248 289
    {
249 75
        $list = [];
250 75
        foreach ($tableForeignKeys as $value) {
251 75
            $value = array_change_key_case($value, CASE_LOWER);
252 67
            if (! isset($list[$value['constraint_name']])) {
253
                if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
254 75
                    $value['delete_rule'] = null;
255 75
                }
256
                if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
257
                    $value['update_rule'] = null;
258 75
                }
259 75
260
                $list[$value['constraint_name']] = [
261
                    'name' => $value['constraint_name'],
262 75
                    'local' => [],
263 75
                    'foreign' => [],
264 75
                    'foreignTable' => $value['referenced_table_name'],
265
                    'onDelete' => $value['delete_rule'],
266
                    'onUpdate' => $value['update_rule'],
267 75
                ];
268 75
            }
269
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
270
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
271 289
        }
272 289
273 75
        $result = [];
274 75
        foreach ($list as $constraint) {
275 75
            $result[] = new ForeignKeyConstraint(
276 75
                array_values($constraint['local']),
277 75
                $constraint['foreignTable'],
278
                array_values($constraint['foreign']),
279 75
                $constraint['name'],
280 75
                [
281
                    'onDelete' => $constraint['onDelete'],
282
                    'onUpdate' => $constraint['onUpdate'],
283
                ]
284
            );
285 289
        }
286
287
        return $result;
288
    }
289
290
    public function listTableDetails($tableName)
291
    {
292
        $table = parent::listTableDetails($tableName);
293
294
        /** @var MySqlPlatform $platform */
295
        $platform = $this->_platform;
296
        $sql      = $platform->getListTableMetadataSQL($tableName);
297
298
        $tableOptions = $this->_conn->fetchAssoc($sql);
299
300
        $table->addOption('engine', $tableOptions['ENGINE']);
301
        if ($tableOptions['TABLE_COLLATION'] !== null) {
302
            $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
303
        }
304
        if ($tableOptions['AUTO_INCREMENT'] !== null) {
305
            $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
306
        }
307
        $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
308
309
        if ($tableOptions['CREATE_OPTIONS'] === null) {
310
            return $table;
311
        }
312
313
        $createOptionsString = trim($tableOptions['CREATE_OPTIONS']);
314
315
        $createOptions = [];
316
317
        if ($createOptionsString !== '') {
318
            foreach (explode(' ', $createOptionsString) as $option) {
319
                [$createOption, $value] = explode('=', $option);
320
321
                $createOptions[$createOption] = $value;
322
            }
323
        }
324
325
        $table->addOption('create_options', $createOptions);
326
327
        return $table;
328
    }
329
}
330