Failed Conditions
Push — 2.10.x ( db5afa...61a6b9 )
by Grégoire
27s queued 15s
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 15
Paths 816

Size

Total Lines 74
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 23.8746

Importance

Changes 0
Metric Value
eloc 49
dl 0
loc 74
ccs 31
cts 47
cp 0.6596
rs 2.0055
c 0
b 0
f 0
cc 15
nc 816
nop 1
crap 23.8746

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\DBALException;
6
use Doctrine\DBAL\DriverManager;
7
use Doctrine\DBAL\FetchMode;
8
use Doctrine\DBAL\Types\StringType;
9
use Doctrine\DBAL\Types\TextType;
10
use Doctrine\DBAL\Types\Type;
11
use function array_change_key_case;
12
use function array_map;
13
use function array_reverse;
14
use function array_values;
15
use function explode;
16
use function file_exists;
17
use function preg_match;
18
use function preg_match_all;
19
use function preg_quote;
20
use function preg_replace;
21
use function rtrim;
22
use function sprintf;
23
use function str_replace;
24
use function strpos;
25
use function strtolower;
26
use function trim;
27
use function unlink;
28
use function usort;
29
use const CASE_LOWER;
30
31
/**
32
 * Sqlite SchemaManager.
33
 */
34
class SqliteSchemaManager extends AbstractSchemaManager
35
{
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function dropDatabase($database)
40
    {
41
        if (! file_exists($database)) {
42
            return;
43
        }
44
45
        unlink($database);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function createDatabase($database)
52
    {
53
        $params  = $this->_conn->getParams();
54
        $driver  = $params['driver'];
55
        $options = [
56
            'driver' => $driver,
57
            'path' => $database,
58
        ];
59
        $conn    = DriverManager::getConnection($options);
60
        $conn->connect();
61
        $conn->close();
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function renameTable($name, $newName)
68
    {
69
        $tableDiff            = new TableDiff($name);
70
        $tableDiff->fromTable = $this->listTableDetails($name);
71
        $tableDiff->newName   = $newName;
72
        $this->alterTable($tableDiff);
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
79
    {
80
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($table);
81
        $tableDiff->addedForeignKeys[] = $foreignKey;
82
83
        $this->alterTable($tableDiff);
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
90
    {
91
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
92
        $tableDiff->changedForeignKeys[] = $foreignKey;
93
94
        $this->alterTable($tableDiff);
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function dropForeignKey($foreignKey, $table)
101
    {
102
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
103
        $tableDiff->removedForeignKeys[] = $foreignKey;
104
105
        $this->alterTable($tableDiff);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 36
    public function listTableForeignKeys($table, $database = null)
112
    {
113 36
        if ($database === null) {
114 36
            $database = $this->_conn->getDatabase();
115
        }
116
117 36
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\DBAL\Platforms\...stTableForeignKeysSQL() has too many arguments starting with $database. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

117
        /** @scrutinizer ignore-call */ 
118
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
118 36
        $tableForeignKeys = $this->_conn->fetchAll($sql);
119
120 36
        if (! empty($tableForeignKeys)) {
121
            $createSql = $this->getCreateTableSQL($table);
122
123
            if ($createSql !== null && preg_match_all(
124
                '#
125
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
126
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
127
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
128
                    (?:
129
                        [^,]*?
130
                        (NOT\s+DEFERRABLE|DEFERRABLE)
131
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
132
                    )?#isx',
133
                $createSql,
134
                $match
135
            )) {
136
                $names      = array_reverse($match[1]);
137
                $deferrable = array_reverse($match[2]);
138
                $deferred   = array_reverse($match[3]);
139
            } else {
140
                $names = $deferrable = $deferred = [];
141
            }
142
143
            foreach ($tableForeignKeys as $key => $value) {
144
                $id                                        = $value['id'];
145
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
146
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
147
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
148
            }
149
        }
150
151 36
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157 36
    protected function _getPortableTableDefinition($table)
158
    {
159 36
        return $table['name'];
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     *
165
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
166
     */
167 36
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
168
    {
169 36
        $indexBuffer = [];
170
171
        // fetch primary
172 36
        $stmt       = $this->_conn->executeQuery(sprintf(
173
            'PRAGMA TABLE_INFO (%s)',
174 36
            $this->_conn->quote($tableName)
175
        ));
176 36
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
177
178
        usort($indexArray, static function ($a, $b) {
179
            if ($a['pk'] === $b['pk']) {
180
                return $a['cid'] - $b['cid'];
181
            }
182
183
            return $a['pk'] - $b['pk'];
184 36
        });
185 36
        foreach ($indexArray as $indexColumnRow) {
186 36
            if ($indexColumnRow['pk'] === '0') {
187
                continue;
188
            }
189
190 36
            $indexBuffer[] = [
191 36
                'key_name' => 'primary',
192
                'primary' => true,
193
                'non_unique' => false,
194 36
                'column_name' => $indexColumnRow['name'],
195
            ];
196
        }
197
198
        // fetch regular indexes
199 36
        foreach ($tableIndexes as $tableIndex) {
200
            // Ignore indexes with reserved names, e.g. autoindexes
201
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
202
                continue;
203
            }
204
205
            $keyName           = $tableIndex['name'];
206
            $idx               = [];
207
            $idx['key_name']   = $keyName;
208
            $idx['primary']    = false;
209
            $idx['non_unique'] = ! $tableIndex['unique'];
210
211
                $stmt       = $this->_conn->executeQuery(sprintf(
212
                    'PRAGMA INDEX_INFO (%s)',
213
                    $this->_conn->quote($keyName)
214
                ));
215
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
216
217
            foreach ($indexArray as $indexColumnRow) {
218
                $idx['column_name'] = $indexColumnRow['name'];
219
                $indexBuffer[]      = $idx;
220
            }
221
        }
222
223 36
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
224
    }
225
226
    /**
227
     * @deprecated
228
     *
229
     * @param array<string, mixed> $tableIndex
230
     *
231
     * @return array<string, bool|string>
232
     */
233
    protected function _getPortableTableIndexDefinition($tableIndex)
234
    {
235
        return [
236
            'name' => $tableIndex['name'],
237
            'unique' => (bool) $tableIndex['unique'],
238
        ];
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 36
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
245
    {
246 36
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
247
248
        // find column with autoincrement
249 36
        $autoincrementColumn = null;
250 36
        $autoincrementCount  = 0;
251
252 36
        foreach ($tableColumns as $tableColumn) {
253 36
            if ($tableColumn['pk'] === '0') {
254
                continue;
255
            }
256
257 36
            $autoincrementCount++;
258 36
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
259
                continue;
260
            }
261
262 36
            $autoincrementColumn = $tableColumn['name'];
263
        }
264
265 36
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
266 36
            foreach ($list as $column) {
267 36
                if ($autoincrementColumn !== $column->getName()) {
268
                    continue;
269
                }
270
271 36
                $column->setAutoincrement(true);
272
            }
273
        }
274
275
        // inspect column collation and comments
276 36
        $createSql = $this->getCreateTableSQL($table) ?? '';
277
278 36
        foreach ($list as $columnName => $column) {
279 36
            $type = $column->getType();
280
281 36
            if ($type instanceof StringType || $type instanceof TextType) {
282
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
283
            }
284
285 36
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
286
287 36
            if ($comment === null) {
288 36
                continue;
289
            }
290
291
            $type = $this->extractDoctrineTypeFromComment($comment, '');
292
293
            if ($type !== '') {
294
                $column->setType(Type::getType($type));
295
296
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
297
            }
298
299
            $column->setComment($comment);
300
        }
301
302 36
        return $list;
303
    }
304
305
    /**
306
     * {@inheritdoc}
307
     */
308 36
    protected function _getPortableTableColumnDefinition($tableColumn)
309
    {
310 36
        $parts               = explode('(', $tableColumn['type']);
311 36
        $tableColumn['type'] = trim($parts[0]);
312 36
        if (isset($parts[1])) {
313
            $length                = trim($parts[1], ')');
314
            $tableColumn['length'] = $length;
315
        }
316
317 36
        $dbType   = strtolower($tableColumn['type']);
318 36
        $length   = $tableColumn['length'] ?? null;
319 36
        $unsigned = false;
320
321 36
        if (strpos($dbType, ' unsigned') !== false) {
322
            $dbType   = str_replace(' unsigned', '', $dbType);
323
            $unsigned = true;
324
        }
325
326 36
        $fixed   = false;
327 36
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
328 36
        $default = $tableColumn['dflt_value'];
329 36
        if ($default === 'NULL') {
330
            $default = null;
331
        }
332
333 36
        if ($default !== null) {
334
            // SQLite returns the default value as a literal expression, so we need to parse it
335
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
336
                $default = str_replace("''", "'", $matches[1]);
337
            }
338
        }
339
340 36
        $notnull = (bool) $tableColumn['notnull'];
341
342 36
        if (! isset($tableColumn['name'])) {
343
            $tableColumn['name'] = '';
344
        }
345
346 36
        $precision = null;
347 36
        $scale     = null;
348
349
        switch ($dbType) {
350 36
            case 'char':
351
                $fixed = true;
352
                break;
353 36
            case 'float':
354 36
            case 'double':
355 36
            case 'real':
356 36
            case 'decimal':
357 36
            case 'numeric':
358
                if (isset($tableColumn['length'])) {
359
                    if (strpos($tableColumn['length'], ',') === false) {
360
                        $tableColumn['length'] .= ',0';
361
                    }
362
363
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
364
                }
365
366
                $length = null;
367
                break;
368
        }
369
370
        $options = [
371 36
            'length'   => $length,
372 36
            'unsigned' => (bool) $unsigned,
373 36
            'fixed'    => $fixed,
374 36
            'notnull'  => $notnull,
375 36
            'default'  => $default,
376 36
            'precision' => $precision,
377 36
            'scale'     => $scale,
378
            'autoincrement' => false,
379
        ];
380
381 36
        return new Column($tableColumn['name'], Type::getType($type), $options);
382
    }
383
384
    /**
385
     * {@inheritdoc}
386
     */
387
    protected function _getPortableViewDefinition($view)
388
    {
389
        return new View($view['name'], $view['sql']);
390
    }
391
392
    /**
393
     * {@inheritdoc}
394
     */
395 36
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
396
    {
397 36
        $list = [];
398 36
        foreach ($tableForeignKeys as $value) {
399
            $value = array_change_key_case($value, CASE_LOWER);
400
            $name  = $value['constraint_name'];
401
            if (! isset($list[$name])) {
402
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
403
                    $value['on_delete'] = null;
404
                }
405
406
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
407
                    $value['on_update'] = null;
408
                }
409
410
                $list[$name] = [
411
                    'name' => $name,
412
                    'local' => [],
413
                    'foreign' => [],
414
                    'foreignTable' => $value['table'],
415
                    'onDelete' => $value['on_delete'],
416
                    'onUpdate' => $value['on_update'],
417
                    'deferrable' => $value['deferrable'],
418
                    'deferred'=> $value['deferred'],
419
                ];
420
            }
421
422
            $list[$name]['local'][]   = $value['from'];
423
            $list[$name]['foreign'][] = $value['to'];
424
        }
425
426 36
        $result = [];
427 36
        foreach ($list as $constraint) {
428
            $result[] = new ForeignKeyConstraint(
429
                array_values($constraint['local']),
430
                $constraint['foreignTable'],
431
                array_values($constraint['foreign']),
432
                $constraint['name'],
433
                [
434
                    'onDelete' => $constraint['onDelete'],
435
                    'onUpdate' => $constraint['onUpdate'],
436
                    'deferrable' => $constraint['deferrable'],
437
                    'deferred'=> $constraint['deferred'],
438
                ]
439
            );
440
        }
441
442 36
        return $result;
443
    }
444
445
    /**
446
     * @param Table|string $table
447
     *
448
     * @return TableDiff
449
     *
450
     * @throws DBALException
451
     */
452
    private function getTableDiffForAlterForeignKey($table)
453
    {
454
        if (! $table instanceof Table) {
455
            $tableDetails = $this->tryMethod('listTableDetails', $table);
456
457
            if ($tableDetails === false) {
458
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
459
            }
460
461
            $table = $tableDetails;
462
        }
463
464
        $tableDiff            = new TableDiff($table->getName());
465
        $tableDiff->fromTable = $table;
466
467
        return $tableDiff;
468
    }
469
470 558
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
471
    {
472 558
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
473 558
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
474
475 558
        if (preg_match($pattern, $sql, $match) !== 1) {
476 540
            return null;
477
        }
478
479 558
        return $match[1];
480
    }
481
482 36
    private function parseTableCommentFromSQL(string $table, string $sql) : ?string
483
    {
484
        $pattern = '/\s* # Allow whitespace characters at start of line
485
CREATE\sTABLE # Match "CREATE TABLE"
486 36
(?:\W"' . preg_quote($this->_platform->quoteSingleIdentifier($table), '/') . '"\W|\W' . preg_quote($table, '/')
487 36
            . '\W) # Match table name (quoted and unquoted)
488
( # Start capture
489
   (?:\s*--[^\n]*\n?)+ # Capture anything that starts with whitespaces followed by -- until the end of the line(s)
490
)/ix';
491
492 36
        if (preg_match($pattern, $sql, $match) !== 1) {
493 36
            return null;
494
        }
495
496
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
497
498
        return $comment === '' ? null : $comment;
499
    }
500
501 378
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
502
    {
503 378
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
504 378
            . '\W)(?:\([^)]*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
505
506 378
        if (preg_match($pattern, $sql, $match) !== 1) {
507 360
            return null;
508
        }
509
510 378
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
511
512 378
        return $comment === '' ? null : $comment;
513
    }
514
515 36
    private function getCreateTableSQL(string $table) : ?string
516
    {
517 36
        return $this->_conn->fetchColumn(
518
            <<<'SQL'
519 36
SELECT sql
520
  FROM (
521
      SELECT *
522
        FROM sqlite_master
523
   UNION ALL
524
      SELECT *
525
        FROM sqlite_temp_master
526
  )
527
WHERE type = 'table'
528
AND name = ?
529
SQL
530
            ,
531 36
            [$table]
532 36
        ) ?: null;
533
    }
534
535
    /**
536
     * @param string $tableName
537
     */
538 36
    public function listTableDetails($tableName) : Table
539
    {
540 36
        $table = parent::listTableDetails($tableName);
541
542 36
        $tableCreateSql = $this->getCreateTableSQL($tableName) ?? '';
543
544 36
        $comment = $this->parseTableCommentFromSQL($tableName, $tableCreateSql);
545
546 36
        if ($comment !== null) {
547
            $table->addOption('comment', $comment);
548
        }
549
550 36
        return $table;
551
    }
552
}
553