Failed Conditions
Pull Request — master (#2825)
by Sébastien
05:16
created

MySqlSchemaManager   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 240
Duplicated Lines 5.42 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 64.05%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 56
c 1
b 0
f 0
lcom 1
cbo 6
dl 13
loc 240
ccs 82
cts 128
cp 0.6405
rs 6.5957

8 Methods

Rating   Name   Duplication   Size   Complexity  
A _getPortableViewDefinition() 0 4 1
A _getPortableTableDefinition() 0 4 1
A _getPortableUserDefinition() 0 7 1
B _getPortableTableIndexesList() 0 19 5
A _getPortableSequenceDefinition() 0 4 1
A _getPortableDatabaseDefinition() 0 4 1
F _getPortableTableColumnDefinition() 13 124 38
C _getPortableTableForeignKeysList() 0 40 8

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like MySqlSchemaManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MySqlSchemaManager, and based on these observations, apply Extract Interface, too.

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\MariaDb102Platform;
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']);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Doctrine\DBA...ew['VIEW_DEFINITION']); (Doctrine\DBAL\Schema\View) is incompatible with the return type of the parent method Doctrine\DBAL\Schema\Abs...tPortableViewDefinition of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
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 1
    protected function _getPortableTableColumnDefinition($tableColumn)
107
    {
108 1
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
109
110 1
        $dbType = strtolower($tableColumn['type']);
111 1
        $dbType = strtok($dbType, '(), ');
112 1
        if (isset($tableColumn['length'])) {
113
            $length = $tableColumn['length'];
114
        } else {
115 1
            $length = strtok('(), ');
116
        }
117
118 1
        $fixed = null;
119
120 1
        if ( ! isset($tableColumn['name'])) {
121 1
            $tableColumn['name'] = '';
122
        }
123
124 1
        $scale = null;
125 1
        $precision = null;
126
127 1
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
128
129
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
130 1 View Code Duplication
        if (isset($tableColumn['comment'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131 1
            $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
132 1
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
133
        }
134
135
        switch ($dbType) {
136 1
            case 'char':
137 1
            case 'binary':
138
                $fixed = true;
139
                break;
140 1
            case 'float':
141 1
            case 'double':
142 1
            case 'real':
143 1
            case 'numeric':
144 1
            case 'decimal':
145 View Code Duplication
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
146
                    $precision = $match[1];
147
                    $scale = $match[2];
148
                    $length = null;
149
                }
150
                break;
151 1
            case 'tinytext':
152
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
153
                break;
154 1
            case 'text':
155
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
156
                break;
157 1
            case 'mediumtext':
158
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
159
                break;
160 1
            case 'tinyblob':
161
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
162
                break;
163 1
            case 'blob':
164
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
165
                break;
166 1
            case 'mediumblob':
167
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
168
                break;
169 1
            case 'tinyint':
170 1
            case 'smallint':
171 1
            case 'mediumint':
172 1
            case 'int':
173 1
            case 'integer':
174 1
            case 'bigint':
175 1
            case 'year':
176 1
                $length = null;
177 1
                break;
178
        }
179
180 1
        $length = ((int) $length == 0) ? null : (int) $length;
181
182
183
184
185
        // For MariaDB >= 10.2.7
186 1
        if ($this->_platform instanceof MariaDb102Platform) {
187
188 1
            $columnDefault = $tableColumn['default'] === 'NULL' ? null : $tableColumn['default'];
189 1
            if ($columnDefault !== null && $columnDefault !== "NULL") {
190
                // Get an unquoted version
191 1
                if ($columnDefault[0] === '"') {
192
                    $columnDefault = preg_replace('/^"(.*)"$/', '$1', stripcslashes($columnDefault));
193 1
                } elseif ($columnDefault[0] === "'") {
194 1
                    $columnDefault = preg_replace('/^\'(.*)\'$/', '$1', stripcslashes($columnDefault));
195
                }
196
197
            }
198
        } else {
199
            // Regular MySQL
200 1
            $columnDefault = (isset($tableColumn['default'])) ? $tableColumn['default'] : null;
201
        }
202
203
        $options = [
204 1
            'length'        => $length,
205 1
            'unsigned'      => (bool) (strpos($tableColumn['type'], 'unsigned') !== false),
206 1
            'fixed'         => (bool) $fixed,
207 1
            'default'       => $columnDefault,
208 1
            'notnull'       => (bool) ($tableColumn['null'] !== 'YES'),
209
            'scale'         => null,
210
            'precision'     => null,
211 1
            'autoincrement' => (bool) (strpos($tableColumn['extra'], 'auto_increment') !== false),
212 1
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
213 1
                ? $tableColumn['comment']
214
                : null,
215
        ];
216
217 1 View Code Duplication
        if ($scale !== null && $precision !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
            $options['scale'] = $scale;
219
            $options['precision'] = $precision;
220
        }
221
222 1
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
223
224 1
        if (isset($tableColumn['collation'])) {
225 1
            $column->setPlatformOption('collation', $tableColumn['collation']);
226
        }
227
228 1
        return $column;
229
    }
230
231
    /**
232
     * {@inheritdoc}
233
     */
234 1
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
235
    {
236 1
        $list = [];
237 1
        foreach ($tableForeignKeys as $value) {
238 1
            $value = array_change_key_case($value, CASE_LOWER);
239 1
            if (!isset($list[$value['constraint_name']])) {
240 1
                if (!isset($value['delete_rule']) || $value['delete_rule'] == "RESTRICT") {
241 1
                    $value['delete_rule'] = null;
242
                }
243 1
                if (!isset($value['update_rule']) || $value['update_rule'] == "RESTRICT") {
244 1
                    $value['update_rule'] = null;
245
                }
246
247 1
                $list[$value['constraint_name']] = [
248 1
                    'name' => $value['constraint_name'],
249
                    'local' => [],
250
                    'foreign' => [],
251 1
                    'foreignTable' => $value['referenced_table_name'],
252 1
                    'onDelete' => $value['delete_rule'],
253 1
                    'onUpdate' => $value['update_rule'],
254
                ];
255
            }
256 1
            $list[$value['constraint_name']]['local'][] = $value['column_name'];
257 1
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
258
        }
259
260 1
        $result = [];
261 1
        foreach ($list as $constraint) {
262 1
            $result[] = new ForeignKeyConstraint(
263 1
                array_values($constraint['local']), $constraint['foreignTable'],
264 1
                array_values($constraint['foreign']), $constraint['name'],
265
                [
266 1
                    'onDelete' => $constraint['onDelete'],
267 1
                    'onUpdate' => $constraint['onUpdate'],
268
                ]
269
            );
270
        }
271
272 1
        return $result;
273
    }
274
}
275