Completed
Push — master ( 9728d9...4d9a08 )
by Sergei
27s queued 16s
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 29
Paths 3328

Size

Total Lines 97
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 71
CRAP Score 29.0558

Importance

Changes 0
Metric Value
eloc 76
c 0
b 0
f 0
dl 0
loc 97
ccs 71
cts 74
cp 0.9595
rs 0
cc 29
nc 3328
nop 1
crap 29.0558

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