Completed
Pull Request — master (#2825)
by Sébastien
04:39
created

MySqlSchemaManager   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 226
Duplicated Lines 5.75 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 63.71%

Importance

Changes 0
Metric Value
wmc 52
lcom 1
cbo 6
dl 13
loc 226
ccs 79
cts 124
cp 0.6371
rs 7.9487
c 0
b 0
f 0

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 110 34
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\MySqlPlatform;
23
use Doctrine\DBAL\Types\Type;
24
25
/**
26
 * Schema manager for the MySql RDBMS.
27
 *
28
 * @author Konsta Vesterinen <[email protected]>
29
 * @author Lukas Smith <[email protected]> (PEAR MDB2 library)
30
 * @author Roman Borschel <[email protected]>
31
 * @author Benjamin Eberlei <[email protected]>
32
 * @since  2.0
33
 */
34
class MySqlSchemaManager extends AbstractSchemaManager
35
{
36
    /**
37
     * {@inheritdoc}
38
     */
39
    protected function _getPortableViewDefinition($view)
40
    {
41
        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...
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    protected function _getPortableTableDefinition($table)
48
    {
49
        return array_shift($table);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    protected function _getPortableUserDefinition($user)
56
    {
57
        return [
58
            'user' => $user['User'],
59
            'password' => $user['Password'],
60
        ];
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
67
    {
68
        foreach ($tableIndexes as $k => $v) {
69
            $v = array_change_key_case($v, CASE_LOWER);
70
            if ($v['key_name'] == 'PRIMARY') {
71
                $v['primary'] = true;
72
            } else {
73
                $v['primary'] = false;
74
            }
75
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
76
                $v['flags'] = ['FULLTEXT'];
77
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
78
                $v['flags'] = ['SPATIAL'];
79
            }
80
            $tableIndexes[$k] = $v;
81
        }
82
83
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    protected function _getPortableSequenceDefinition($sequence)
90
    {
91
        return end($sequence);
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    protected function _getPortableDatabaseDefinition($database)
98
    {
99
        return $database['Database'];
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105 1
    protected function _getPortableTableColumnDefinition($tableColumn)
106
    {
107 1
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
108
109 1
        $dbType = strtolower($tableColumn['type']);
110 1
        $dbType = strtok($dbType, '(), ');
111 1
        if (isset($tableColumn['length'])) {
112
            $length = $tableColumn['length'];
113
        } else {
114 1
            $length = strtok('(), ');
115
        }
116
117 1
        $fixed = null;
118
119 1
        if ( ! isset($tableColumn['name'])) {
120 1
            $tableColumn['name'] = '';
121
        }
122
123 1
        $scale = null;
124 1
        $precision = null;
125
126 1
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
127
128
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
129 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...
130 1
            $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
131 1
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
132
        }
133
134
        switch ($dbType) {
135 1
            case 'char':
136 1
            case 'binary':
137
                $fixed = true;
138
                break;
139 1
            case 'float':
140 1
            case 'double':
141 1
            case 'real':
142 1
            case 'numeric':
143 1
            case 'decimal':
144 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...
145
                    $precision = $match[1];
146
                    $scale = $match[2];
147
                    $length = null;
148
                }
149
                break;
150 1
            case 'tinytext':
151
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
152
                break;
153 1
            case 'text':
154
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
155
                break;
156 1
            case 'mediumtext':
157
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
158
                break;
159 1
            case 'tinyblob':
160
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
161
                break;
162 1
            case 'blob':
163
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
164
                break;
165 1
            case 'mediumblob':
166
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
167
                break;
168 1
            case 'tinyint':
169 1
            case 'smallint':
170 1
            case 'mediumint':
171 1
            case 'int':
172 1
            case 'integer':
173 1
            case 'bigint':
174 1
            case 'year':
175 1
                $length = null;
176 1
                break;
177
        }
178
179 1
        $length = ((int) $length == 0) ? null : (int) $length;
180
181 1
        $isNotNull = ($tableColumn['null'] !== 'YES');
182 1
        $columnDefault = (isset($tableColumn['default'])) ? $tableColumn['default'] : null;
183 1
        if ($columnDefault === 'NULL' && !$isNotNull) {
184
            // for mariadb 10.2.7
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
185 1
            $columnDefault = null;
186
        }
187
188
        $options = [
189 1
            'length'        => $length,
190 1
            'unsigned'      => (bool) (strpos($tableColumn['type'], 'unsigned') !== false),
191 1
            'fixed'         => (bool) $fixed,
192 1
            'default'       => $columnDefault,
193 1
            'notnull'       => $isNotNull,
194
            'scale'         => null,
195
            'precision'     => null,
196 1
            'autoincrement' => (bool) (strpos($tableColumn['extra'], 'auto_increment') !== false),
197 1
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
198 1
                ? $tableColumn['comment']
199
                : null,
200
        ];
201
202 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...
203
            $options['scale'] = $scale;
204
            $options['precision'] = $precision;
205
        }
206
207 1
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
208
209 1
        if (isset($tableColumn['collation'])) {
210 1
            $column->setPlatformOption('collation', $tableColumn['collation']);
211
        }
212
213 1
        return $column;
214
    }
215
216
    /**
217
     * {@inheritdoc}
218
     */
219 1
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
220
    {
221 1
        $list = [];
222 1
        foreach ($tableForeignKeys as $value) {
223 1
            $value = array_change_key_case($value, CASE_LOWER);
224 1
            if (!isset($list[$value['constraint_name']])) {
225 1
                if (!isset($value['delete_rule']) || $value['delete_rule'] == "RESTRICT") {
226 1
                    $value['delete_rule'] = null;
227
                }
228 1
                if (!isset($value['update_rule']) || $value['update_rule'] == "RESTRICT") {
229 1
                    $value['update_rule'] = null;
230
                }
231
232 1
                $list[$value['constraint_name']] = [
233 1
                    'name' => $value['constraint_name'],
234
                    'local' => [],
235
                    'foreign' => [],
236 1
                    'foreignTable' => $value['referenced_table_name'],
237 1
                    'onDelete' => $value['delete_rule'],
238 1
                    'onUpdate' => $value['update_rule'],
239
                ];
240
            }
241 1
            $list[$value['constraint_name']]['local'][] = $value['column_name'];
242 1
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
243
        }
244
245 1
        $result = [];
246 1
        foreach ($list as $constraint) {
247 1
            $result[] = new ForeignKeyConstraint(
248 1
                array_values($constraint['local']), $constraint['foreignTable'],
249 1
                array_values($constraint['foreign']), $constraint['name'],
250
                [
251 1
                    'onDelete' => $constraint['onDelete'],
252 1
                    'onUpdate' => $constraint['onUpdate'],
253
                ]
254
            );
255
        }
256
257 1
        return $result;
258
    }
259
}
260