Passed
Push — drop-deprecated ( db0b1f )
by Michael
27:00
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 31
Paths 6656

Size

Total Lines 102
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 53
CRAP Score 55.247

Importance

Changes 0
Metric Value
eloc 79
dl 0
loc 102
ccs 53
cts 75
cp 0.7067
rs 0
c 0
b 0
f 0
cc 31
nc 6656
nop 1
crap 55.247

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