Passed
Push — master ( ce4534...130fa4 )
by Sergei
12:18
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 31
Paths 6656

Size

Total Lines 102
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 71
CRAP Score 31.0638

Importance

Changes 0
Metric Value
eloc 78
dl 0
loc 102
ccs 71
cts 74
cp 0.9595
rs 0
c 0
b 0
f 0
cc 31
nc 6656
nop 1
crap 31.0638

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 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
     * {@inheritdoc}
30
     */
31 8
    protected function _getPortableViewDefinition($view)
32
    {
33 8
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 606
    protected function _getPortableTableDefinition($table)
40
    {
41 606
        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
     * {@inheritdoc}
57
     */
58 318
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
59
    {
60 318
        foreach ($tableIndexes as $k => $v) {
61 176
            $v = array_change_key_case($v, CASE_LOWER);
62 176
            if ($v['key_name'] === 'PRIMARY') {
63 136
                $v['primary'] = true;
64
            } else {
65 112
                $v['primary'] = false;
66
            }
67 176
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
68 24
                $v['flags'] = ['FULLTEXT'];
69 168
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
70 24
                $v['flags'] = ['SPATIAL'];
71
            }
72 176
            $v['length'] = $v['sub_part'] ?? null;
73
74 176
            $tableIndexes[$k] = $v;
75
        }
76
77 318
        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
     * {@inheritdoc}
90
     */
91 16
    protected function _getPortableDatabaseDefinition($database)
92
    {
93 16
        return $database['Database'];
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 382
    protected function _getPortableTableColumnDefinition($tableColumn)
100
    {
101 382
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
102
103 382
        $dbType = strtolower($tableColumn['type']);
104 382
        $dbType = strtok($dbType, '(), ');
105 382
        $length = $tableColumn['length'] ?? strtok('(), ');
106
107 382
        $fixed = null;
108
109 382
        if (! isset($tableColumn['name'])) {
110 382
            $tableColumn['name'] = '';
111
        }
112
113 382
        $scale     = null;
114 382
        $precision = null;
115
116 382
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
117
118
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
119 382
        if (isset($tableColumn['comment'])) {
120 382
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
121 382
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
122
        }
123
124
        switch ($dbType) {
125 382
            case 'char':
126 366
            case 'binary':
127 48
                $fixed = true;
128 48
                break;
129 366
            case 'float':
130 366
            case 'double':
131 358
            case 'real':
132 358
            case 'numeric':
133 358
            case 'decimal':
134 56
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
135 48
                    $precision = $match[1];
136 48
                    $scale     = $match[2];
137 48
                    $length    = null;
138
                }
139 56
                break;
140 350
            case 'tinytext':
141 24
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
142 24
                break;
143 350
            case 'text':
144 24
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
145 24
                break;
146 350
            case 'mediumtext':
147 24
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
148 24
                break;
149 350
            case 'tinyblob':
150
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
151
                break;
152 350
            case 'blob':
153 24
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
154 24
                break;
155 350
            case 'mediumblob':
156 24
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
157 24
                break;
158 350
            case 'tinyint':
159 350
            case 'smallint':
160 350
            case 'mediumint':
161 350
            case 'int':
162 182
            case 'integer':
163 182
            case 'bigint':
164 182
            case 'year':
165 288
                $length = null;
166 288
                break;
167
        }
168
169 382
        if ($this->_platform instanceof MariaDb1027Platform) {
170 94
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
171
        } else {
172 288
            $columnDefault = $tableColumn['default'];
173
        }
174
175
        $options = [
176 382
            'length'        => $length !== null ? (int) $length : null,
177 382
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
178 382
            'fixed'         => (bool) $fixed,
179 382
            'default'       => $columnDefault,
180 382
            'notnull'       => $tableColumn['null'] !== 'YES',
181
            'scale'         => null,
182
            'precision'     => null,
183 382
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
184 382
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
185 112
                ? $tableColumn['comment']
186
                : null,
187
        ];
188
189 382
        if ($scale !== null && $precision !== null) {
190 48
            $options['scale']     = (int) $scale;
191 48
            $options['precision'] = (int) $precision;
192
        }
193
194 382
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
195
196 382
        if (isset($tableColumn['collation'])) {
197 168
            $column->setPlatformOption('collation', $tableColumn['collation']);
198
        }
199
200 382
        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
     * @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
218
     */
219 94
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
220
    {
221 94
        if ($columnDefault === 'NULL' || $columnDefault === null) {
222 86
            return null;
223
        }
224 20
        if ($columnDefault[0] === "'") {
225 16
            return stripslashes(
226 16
                str_replace(
227 16
                    "''",
228 16
                    "'",
229 16
                    preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
230
                )
231
            );
232
        }
233
        switch ($columnDefault) {
234 12
            case 'current_timestamp()':
235 8
                return $platform->getCurrentTimestampSQL();
236 10
            case 'curdate()':
237 6
                return $platform->getCurrentDateSQL();
238 10
            case 'curtime()':
239 6
                return $platform->getCurrentTimeSQL();
240
        }
241 8
        return $columnDefault;
242
    }
243
244
    /**
245
     * {@inheritdoc}
246
     */
247 305
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
248
    {
249 305
        $list = [];
250 305
        foreach ($tableForeignKeys as $value) {
251 75
            $value = array_change_key_case($value, CASE_LOWER);
252 75
            if (! isset($list[$value['constraint_name']])) {
253 75
                if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
254 67
                    $value['delete_rule'] = null;
255
                }
256 75
                if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
257 75
                    $value['update_rule'] = null;
258
                }
259
260 75
                $list[$value['constraint_name']] = [
261 75
                    'name' => $value['constraint_name'],
262
                    'local' => [],
263
                    'foreign' => [],
264 75
                    'foreignTable' => $value['referenced_table_name'],
265 75
                    'onDelete' => $value['delete_rule'],
266 75
                    'onUpdate' => $value['update_rule'],
267
                ];
268
            }
269 75
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
270 75
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
271
        }
272
273 305
        $result = [];
274 305
        foreach ($list as $constraint) {
275 75
            $result[] = new ForeignKeyConstraint(
276 75
                array_values($constraint['local']),
277 75
                $constraint['foreignTable'],
278 75
                array_values($constraint['foreign']),
279 75
                $constraint['name'],
280
                [
281 75
                    'onDelete' => $constraint['onDelete'],
282 75
                    'onUpdate' => $constraint['onUpdate'],
283
                ]
284
            );
285
        }
286
287 305
        return $result;
288
    }
289
290 270
    public function listTableDetails($tableName)
291
    {
292 270
        $table = parent::listTableDetails($tableName);
293
294
        /** @var MySqlPlatform $platform */
295 270
        $platform = $this->_platform;
296 270
        $sql      = $platform->getListTableMetadataSQL($tableName);
297
298 270
        $tableOptions = $this->_conn->fetchAssoc($sql);
299
300 270
        $table->addOption('engine', $tableOptions['ENGINE']);
301 270
        if ($tableOptions['TABLE_COLLATION'] !== null) {
302 270
            $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
303
        }
304 270
        if ($tableOptions['AUTO_INCREMENT'] !== null) {
305 32
            $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
306
        }
307 270
        $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
308
309 270
        if ($tableOptions['CREATE_OPTIONS'] === null) {
310
            return $table;
311
        }
312
313 270
        $createOptionsString = trim($tableOptions['CREATE_OPTIONS']);
314
315 270
        $createOptions = [];
316
317 270
        if ($createOptionsString !== '') {
318 24
            foreach (explode(' ', $createOptionsString) as $option) {
319 24
                [$createOption, $value] = explode('=', $option);
320
321 24
                $createOptions[$createOption] = $value;
322
            }
323
        }
324
325 270
        $table->addOption('create_options', $createOptions);
326
327 270
        return $table;
328
    }
329
}
330