Failed Conditions
Pull Request — develop (#3348)
by Sergei
22:47
created

_getPortableTableColumnDefinition()   D

Complexity

Conditions 10
Paths 384

Size

Total Lines 56
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 10.003

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 56
ccs 31
cts 32
cp 0.9688
rs 4.5333
c 0
b 0
f 0
cc 10
nc 384
nop 1
crap 10.003

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\DBALException;
8
use Doctrine\DBAL\DriverManager;
9
use Doctrine\DBAL\FetchMode;
10
use Doctrine\DBAL\Types\StringType;
11
use Doctrine\DBAL\Types\TextType;
12
use Doctrine\DBAL\Types\Type;
13
use const CASE_LOWER;
14
use function array_change_key_case;
15
use function array_reverse;
16
use function array_values;
17
use function count;
18
use function file_exists;
19
use function preg_match;
20
use function preg_match_all;
21
use function preg_quote;
22
use function preg_replace;
23
use function rtrim;
24
use function sprintf;
25
use function strpos;
26
use function strtolower;
27
use function unlink;
28
use function usort;
29
30
/**
31
 * Sqlite SchemaManager.
32
 */
33
class SqliteSchemaManager extends AbstractSchemaManager
34
{
35
    /**
36
     * {@inheritdoc}
37
     */
38 87
    public function dropDatabase(string $database) : void
39
    {
40 87
        if (! file_exists($database)) {
41 86
            return;
42
        }
43
44 87
        unlink($database);
45 87
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 87
    public function createDatabase(string $database) : void
51
    {
52 87
        $params  = $this->_conn->getParams();
53 87
        $driver  = $params['driver'];
54
        $options = [
55 87
            'driver' => $driver,
56 87
            'path' => $database,
57
        ];
58 87
        $conn    = DriverManager::getConnection($options);
59 87
        $conn->connect();
60 87
        $conn->close();
61 87
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 85
    public function renameTable(string $name, string $newName) : void
67
    {
68 85
        $tableDiff            = new TableDiff($name);
69 85
        $tableDiff->fromTable = $this->listTableDetails($name);
70 85
        $tableDiff->newName   = $newName;
71 85
        $this->alterTable($tableDiff);
72 85
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table) : void
78
    {
79
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($table);
80
        $tableDiff->addedForeignKeys[] = $foreignKey;
81
82
        $this->alterTable($tableDiff);
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table) : void
89
    {
90
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
91
        $tableDiff->changedForeignKeys[] = $foreignKey;
92
93
        $this->alterTable($tableDiff);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function dropForeignKey($foreignKey, $table) : void
100
    {
101
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
102
        $tableDiff->removedForeignKeys[] = $foreignKey;
103
104
        $this->alterTable($tableDiff);
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 84
    public function listTableForeignKeys(string $table, ?string $database = null) : array
111
    {
112 84
        if ($database === null) {
113 84
            $database = $this->_conn->getDatabase();
114
        }
115 84
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
116 84
        $tableForeignKeys = $this->_conn->fetchAll($sql);
117
118 84
        if (! empty($tableForeignKeys)) {
119 84
            $createSql = $this->getCreateTableSQL($table);
120
121 84
            if ($createSql !== null && preg_match_all(
122
                '#
123
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
124
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
125
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
126
                    (?:
127
                        [^,]*?
128
                        (NOT\s+DEFERRABLE|DEFERRABLE)
129
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
130
                    )?#isx',
131 84
                $createSql,
132 84
                $match
133
            )) {
134 84
                $names      = array_reverse($match[1]);
135 84
                $deferrable = array_reverse($match[2]);
136 84
                $deferred   = array_reverse($match[3]);
137
            } else {
138
                $names = $deferrable = $deferred = [];
139
            }
140
141 84
            foreach ($tableForeignKeys as $key => $value) {
142 84
                $id                                        = $value['id'];
143 84
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
144 84
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
145 84
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
146
            }
147
        }
148
149 84
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155 145
    protected function _getPortableTableDefinition($table) : string
156
    {
157 145
        return $table['name'];
158
    }
159
160
    /**
161
     * {@inheritdoc}
162
     *
163
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
164
     */
165 138
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
166
    {
167 138
        $indexBuffer = [];
168
169
        // fetch primary
170 138
        $stmt       = $this->_conn->executeQuery(sprintf(
171 2
            'PRAGMA TABLE_INFO (%s)',
172 138
            $this->_conn->quote($tableName)
173
        ));
174 138
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
175
176
        usort($indexArray, static function ($a, $b) {
177 85
            if ($a['pk'] === $b['pk']) {
178 85
                return $a['cid'] - $b['cid'];
179
            }
180
181 85
            return $a['pk'] - $b['pk'];
182 138
        });
183 138
        foreach ($indexArray as $indexColumnRow) {
184 138
            if ($indexColumnRow['pk'] === '0') {
185 90
                continue;
186
            }
187
188 133
            $indexBuffer[] = [
189 133
                'key_name' => 'primary',
190
                'primary' => true,
191
                'non_unique' => false,
192 133
                'column_name' => $indexColumnRow['name'],
193
            ];
194
        }
195
196
        // fetch regular indexes
197 138
        foreach ($tableIndexRows as $tableIndex) {
198
            // Ignore indexes with reserved names, e.g. autoindexes
199 81
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
200 81
                continue;
201
            }
202
203 72
            $keyName           = $tableIndex['name'];
204 72
            $idx               = [];
205 72
            $idx['key_name']   = $keyName;
206 72
            $idx['primary']    = false;
207 72
            $idx['non_unique'] = ! $tableIndex['unique'];
208
209 72
                $stmt       = $this->_conn->executeQuery(sprintf(
210
                    'PRAGMA INDEX_INFO (%s)',
211 72
                    $this->_conn->quote($keyName)
212
                ));
213 72
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
214
215 72
            foreach ($indexArray as $indexColumnRow) {
216 72
                $idx['column_name'] = $indexColumnRow['name'];
217 72
                $indexBuffer[]      = $idx;
218
            }
219
        }
220
221 138
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
222
    }
223
224
    /**
225
     * {@inheritdoc}
226
     */
227
    protected function _getPortableTableIndexDefinition($tableIndex) : array
228
    {
229
        return [
230
            'name' => $tableIndex['name'],
231
            'unique' => (bool) $tableIndex['unique'],
232
        ];
233
    }
234
235
    /**
236
     * {@inheritdoc}
237
     */
238 138
    protected function _getPortableTableColumnList(string $table, ?string $database, array $tableColumns) : array
239
    {
240 138
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
241
242
        // find column with autoincrement
243 138
        $autoincrementColumn = null;
244 138
        $autoincrementCount  = 0;
245
246 138
        foreach ($tableColumns as $tableColumn) {
247 138
            if ($tableColumn['pk'] === '0') {
248 90
                continue;
249
            }
250
251 133
            $autoincrementCount++;
252 133
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
253 72
                continue;
254
            }
255
256 133
            $autoincrementColumn = $tableColumn['name'];
257
        }
258
259 138
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
260 133
            foreach ($list as $column) {
261 133
                if ($autoincrementColumn !== $column->getName()) {
262 85
                    continue;
263
                }
264
265 133
                $column->setAutoincrement(true);
266
            }
267
        }
268
269
        // inspect column collation and comments
270 138
        $createSql = $this->getCreateTableSQL($table) ?? '';
271
272 138
        foreach ($list as $columnName => $column) {
273 138
            $type = $column->getType();
274
275 138
            if ($type instanceof StringType || $type instanceof TextType) {
276 85
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
277
            }
278
279 138
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
280
281 138
            $type = $this->extractDoctrineTypeFromComment($comment);
282
283 138
            if ($type !== null) {
284 58
                $column->setType(Type::getType($type));
285
            }
286
287 138
            $column->setComment($comment);
288
        }
289
290 138
        return $list;
291
    }
292
293
    /**
294
     * {@inheritdoc}
295
     */
296 138
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
297
    {
298 138
        preg_match('/^([^\\s()]*)\\s*(\\(((\\d+)(,\\s*(\\d+))?)\\))?/', $tableColumn['type'], $matches);
299
300 138
        $dbType = strtolower($matches[1]);
301
302 138
        $length = $precision = $scale = $unsigned = $fixed = null;
303
304 138
        if (count($matches) >= 6) {
305 71
            $precision = (int) $matches[4];
306 71
            $scale     = (int) $matches[6];
307 138
        } elseif (count($matches) >= 4) {
308 85
            $length = (int) $matches[4];
309
        }
310
311 138
        if (strpos($tableColumn['type'], ' UNSIGNED') !== false) {
312 36
            $unsigned = true;
313
        }
314
315 138
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
316 138
        $default = $tableColumn['dflt_value'];
317 138
        if ($default === 'NULL') {
318 71
            $default = null;
319
        }
320 138
        if ($default !== null) {
321
            // SQLite returns strings wrapped in single quotes, so we need to strip them
322 90
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
323
        }
324 138
        $notnull = (bool) $tableColumn['notnull'];
325
326 138
        if (! isset($tableColumn['name'])) {
327
            $tableColumn['name'] = '';
328
        }
329
330 138
        if ($dbType === 'char') {
331 70
            $fixed = true;
332
        }
333
334
        $options = [
335 138
            'length'   => $length,
336 138
            'notnull'  => $notnull,
337 138
            'default'  => $default,
338 138
            'precision' => $precision,
339 138
            'scale'     => $scale,
340
            'autoincrement' => false,
341
        ];
342
343 138
        if ($unsigned !== null) {
344 36
            $options['unsigned'] = $unsigned;
345
        }
346
347 138
        if ($fixed !== null) {
348 70
            $options['fixed'] = $fixed;
349
        }
350
351 138
        return new Column($tableColumn['name'], Type::getType($type), $options);
352
    }
353
354
    /**
355
     * {@inheritdoc}
356
     */
357 62
    protected function _getPortableViewDefinition(array $view) : View
358
    {
359 62
        return new View($view['name'], $view['sql']);
360
    }
361
362
    /**
363
     * {@inheritdoc}
364
     */
365 84
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
366
    {
367 84
        $list = [];
368 84
        foreach ($tableForeignKeys as $value) {
369 84
            $value = array_change_key_case($value, CASE_LOWER);
370 84
            $name  = $value['constraint_name'];
371 84
            if (! isset($list[$name])) {
372 84
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
373
                    $value['on_delete'] = null;
374
                }
375 84
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
376
                    $value['on_update'] = null;
377
                }
378
379 84
                $list[$name] = [
380 84
                    'name' => $name,
381
                    'local' => [],
382
                    'foreign' => [],
383 84
                    'foreignTable' => $value['table'],
384 84
                    'onDelete' => $value['on_delete'],
385 84
                    'onUpdate' => $value['on_update'],
386 84
                    'deferrable' => $value['deferrable'],
387 84
                    'deferred'=> $value['deferred'],
388
                ];
389
            }
390 84
            $list[$name]['local'][] = $value['from'];
391
392 84
            if ($value['to'] === null) {
393 84
                continue;
394
            }
395
396 84
            $list[$name]['foreign'][] = $value['to'];
397
        }
398
399 84
        $result = [];
400 84
        foreach ($list as $constraint) {
401 84
            $result[] = new ForeignKeyConstraint(
402 84
                array_values($constraint['local']),
403 84
                $constraint['foreignTable'],
404 84
                array_values($constraint['foreign']),
405 84
                $constraint['name'],
406
                [
407 84
                    'onDelete' => $constraint['onDelete'],
408 84
                    'onUpdate' => $constraint['onUpdate'],
409 84
                    'deferrable' => $constraint['deferrable'],
410 84
                    'deferred'=> $constraint['deferred'],
411
                ]
412
            );
413
        }
414
415 84
        return $result;
416
    }
417
418
    /**
419
     * @param Table|string $table
420
     *
421
     * @throws DBALException
422
     */
423
    private function getTableDiffForAlterForeignKey($table) : TableDiff
424
    {
425
        if (! $table instanceof Table) {
426
            $tableDetails = $this->tryMethod('listTableDetails', $table);
427
428
            if ($tableDetails === false) {
429
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
430
            }
431
432
            $table = $tableDetails;
433
        }
434
435
        $tableDiff            = new TableDiff($table->getName());
436
        $tableDiff->fromTable = $table;
437
438
        return $tableDiff;
439
    }
440
441 906
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
442
    {
443 906
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
444 906
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
445
446 906
        if (preg_match($pattern, $sql, $match) !== 1) {
447 849
            return null;
448
        }
449
450 899
        return $match[1];
451
    }
452
453 620
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
454
    {
455 620
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
456 620
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
457
458 620
        if (preg_match($pattern, $sql, $match) !== 1) {
459 609
            return null;
460
        }
461
462 576
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
463
464 576
        return $comment === '' ? null : $comment;
465
    }
466
467 138
    private function getCreateTableSQL(string $table) : ?string
468
    {
469 138
        return $this->_conn->fetchColumn(
470
            <<<'SQL'
471 138
SELECT sql
472
  FROM (
473
      SELECT *
474
        FROM sqlite_master
475
   UNION ALL
476
      SELECT *
477
        FROM sqlite_temp_master
478
  )
479
WHERE type = 'table'
480
AND name = ?
481
SQL
482
            ,
483 138
            [$table]
484 138
        ) ?: null;
485
    }
486
}
487