MySqlSchemaManager   F
last analyzed

Complexity

Total Complexity 64

Size/Duplication

Total Lines 319
Duplicated Lines 0 %

Test Coverage

Coverage 82.39%

Importance

Changes 0
Metric Value
wmc 64
eloc 171
dl 0
loc 319
rs 3.28
c 0
b 0
f 0
ccs 131
cts 159
cp 0.8239

10 Methods

Rating   Name   Duplication   Size   Complexity  
A _getPortableTableDefinition() 0 3 1
A _getPortableDatabaseDefinition() 0 3 1
A listTableDetails() 0 21 3
F _getPortableTableColumnDefinition() 0 107 32
B getMariaDb1027ColumnDefault() 0 20 7
B _getPortableTableForeignKeysList() 0 41 8
A _getPortableViewDefinition() 0 3 1
A _getPortableTableIndexesList() 0 20 6
A _getPortableUserDefinition() 0 5 1
A parseCreateOptions() 0 15 4

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