Completed
Pull Request — master (#2412)
by Benoît
20:15
created

MySqlSchemaManager   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 262
Duplicated Lines 0 %

Test Coverage

Coverage 93.62%

Importance

Changes 0
Metric Value
wmc 56
eloc 141
dl 0
loc 262
ccs 132
cts 141
cp 0.9362
rs 5.5199
c 0
b 0
f 0

9 Methods

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

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