Completed
Push — master ( 8575c2...a53269 )
by Marco
02:31 queued 01:15
created

MySqlSchemaManager::getMariaDb1027ColumnDefault()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 7.551
c 0
b 0
f 0
ccs 0
cts 14
cp 0
cc 7
eloc 14
nc 6
nop 2
crap 56
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL\Schema;
21
22
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
23
use Doctrine\DBAL\Platforms\MySqlPlatform;
24
use Doctrine\DBAL\Types\Type;
25
26
/**
27
 * Schema manager for the MySql RDBMS.
28
 *
29
 * @author Konsta Vesterinen <[email protected]>
30
 * @author Lukas Smith <[email protected]> (PEAR MDB2 library)
31
 * @author Roman Borschel <[email protected]>
32
 * @author Benjamin Eberlei <[email protected]>
33
 * @since  2.0
34
 */
35
class MySqlSchemaManager extends AbstractSchemaManager
36
{
37
    /**
38
     * {@inheritdoc}
39
     */
40
    protected function _getPortableViewDefinition($view)
41
    {
42
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    protected function _getPortableTableDefinition($table)
49
    {
50
        return array_shift($table);
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    protected function _getPortableUserDefinition($user)
57
    {
58
        return [
59
            'user' => $user['User'],
60
            'password' => $user['Password'],
61
        ];
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
68
    {
69
        foreach ($tableIndexes as $k => $v) {
70
            $v = array_change_key_case($v, CASE_LOWER);
71
            if ($v['key_name'] === 'PRIMARY') {
72
                $v['primary'] = true;
73
            } else {
74
                $v['primary'] = false;
75
            }
76
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
77
                $v['flags'] = ['FULLTEXT'];
78
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
79
                $v['flags'] = ['SPATIAL'];
80
            }
81
            $tableIndexes[$k] = $v;
82
        }
83
84
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    protected function _getPortableSequenceDefinition($sequence)
91
    {
92
        return end($sequence);
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    protected function _getPortableDatabaseDefinition($database)
99
    {
100
        return $database['Database'];
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    protected function _getPortableTableColumnDefinition($tableColumn)
107
    {
108
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
109
110
        $dbType = strtolower($tableColumn['type']);
111
        $dbType = strtok($dbType, '(), ');
112
        $length = $tableColumn['length'] ?? strtok('(), ');
0 ignored issues
show
Bug introduced by
The call to strtok() has too few arguments starting with token. ( Ignorable by Annotation )

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

112
        $length = $tableColumn['length'] ?? /** @scrutinizer ignore-call */ strtok('(), ');

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
113
114
        $fixed = null;
115
116
        if ( ! isset($tableColumn['name'])) {
117
            $tableColumn['name'] = '';
118
        }
119
120
        $scale     = null;
121
        $precision = null;
122
123
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
124
125
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
126
        if (isset($tableColumn['comment'])) {
127
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
128
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
129
        }
130
131
        switch ($dbType) {
132
            case 'char':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
133
            case 'binary':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
134
                $fixed = true;
135
                break;
136
            case 'float':
137
            case 'double':
138
            case 'real':
139
            case 'numeric':
140
            case 'decimal':
141
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
142
                    $precision = $match[1];
143
                    $scale     = $match[2];
144
                    $length    = null;
145
                }
146
                break;
147
            case 'tinytext':
148
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
149
                break;
150
            case 'text':
151
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
152
                break;
153
            case 'mediumtext':
154
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
155
                break;
156
            case 'tinyblob':
157
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
158
                break;
159
            case 'blob':
160
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
161
                break;
162
            case 'mediumblob':
163
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
164
                break;
165
            case 'tinyint':
166
            case 'smallint':
167
            case 'mediumint':
168
            case 'int':
169
            case 'integer':
170
            case 'bigint':
171
            case 'year':
172
                $length = null;
173
                break;
174
        }
175
176
        if ($this->_platform instanceof MariaDb1027Platform) {
177
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
178
        } else {
179
            $columnDefault = $tableColumn['default'];
180
        }
181
182
        $options = [
183
            'length'        => $length !== null ? (int) $length : null,
184
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
185
            'fixed'         => (bool) $fixed,
186
            'default'       => $columnDefault,
187
            'notnull'       => $tableColumn['null'] !== 'YES',
188
            'scale'         => null,
189
            'precision'     => null,
190
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
191
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
192
                ? $tableColumn['comment']
193
                : null,
194
        ];
195
196
        if ($scale !== null && $precision !== null) {
197
            $options['scale']     = (int) $scale;
198
            $options['precision'] = (int) $precision;
199
        }
200
201
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
202
203
        if (isset($tableColumn['collation'])) {
204
            $column->setPlatformOption('collation', $tableColumn['collation']);
205
        }
206
207
        return $column;
208
    }
209
210
    /**
211
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
212
     *
213
     * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
214
     *   to distinguish them from expressions (see MDEV-10134).
215
     * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
216
     *   as current_timestamp(), currdate(), currtime()
217
     * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
218
     *   null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
219
     * - \' is always stored as '' in information_schema (normalized)
220
     *
221
     * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
222
     * @link https://jira.mariadb.org/browse/MDEV-13132
223
     *
224
     * @param null|string $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
225
     */
226
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
227
    {
228
        if ($columnDefault === 'NULL' || $columnDefault === null) {
229
            return null;
230
        }
231
        if ($columnDefault[0] === "'") {
232
            return stripslashes(
233
                str_replace("''", "'",
234
                    preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
235
                )
236
            );
237
        }
238
        switch ($columnDefault) {
239
            case 'current_timestamp()':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
240
                return $platform->getCurrentTimestampSQL();
241
            case 'curdate()':
242
                return $platform->getCurrentDateSQL();
243
            case 'curtime()':
244
                return $platform->getCurrentTimeSQL();
245
        }
246
        return $columnDefault;
247
    }
248
249
    /**
250
     * {@inheritdoc}
251
     */
252 1
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
253
    {
254 1
        $list = [];
255 1
        foreach ($tableForeignKeys as $value) {
256 1
            $value = array_change_key_case($value, CASE_LOWER);
257 1
            if ( ! isset($list[$value['constraint_name']])) {
258 1
                if ( ! isset($value['delete_rule']) || $value['delete_rule'] === "RESTRICT") {
259 1
                    $value['delete_rule'] = null;
260
                }
261 1
                if ( ! isset($value['update_rule']) || $value['update_rule'] === "RESTRICT") {
262 1
                    $value['update_rule'] = null;
263
                }
264
265 1
                $list[$value['constraint_name']] = [
266 1
                    'name' => $value['constraint_name'],
267
                    'local' => [],
268
                    'foreign' => [],
269 1
                    'foreignTable' => $value['referenced_table_name'],
270 1
                    'onDelete' => $value['delete_rule'],
271 1
                    'onUpdate' => $value['update_rule'],
272
                ];
273
            }
274 1
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
275 1
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
276
        }
277
278 1
        $result = [];
279 1
        foreach ($list as $constraint) {
280 1
            $result[] = new ForeignKeyConstraint(
281 1
                array_values($constraint['local']),
282 1
                $constraint['foreignTable'],
283 1
                array_values($constraint['foreign']),
284 1
                $constraint['name'],
285
                [
286 1
                    'onDelete' => $constraint['onDelete'],
287 1
                    'onUpdate' => $constraint['onUpdate'],
288
                ]
289
            );
290
        }
291
292 1
        return $result;
293
    }
294
}
295