Completed
Push — develop ( 90495a...4ed75b )
by Sergei
25s queued 13s
created

_getPortableTableColumnDefinition()   B

Complexity

Conditions 8
Paths 96

Size

Total Lines 53
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 8.0101

Importance

Changes 0
Metric Value
eloc 34
dl 0
loc 53
ccs 35
cts 37
cp 0.9459
rs 8.1315
c 0
b 0
f 0
cc 8
nc 96
nop 1
crap 8.0101

How to fix   Long Method   

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