MySqlSchemaManager   F
last analyzed

Complexity

Total Complexity 64

Size/Duplication

Total Lines 299
Duplicated Lines 0 %

Test Coverage

Coverage 82.39%

Importance

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