GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Setup Failed
Push — master ( 87ff8e...b9de50 )
by Albert
02:55
created

DbMigrations   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 296
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 40
lcom 1
cbo 4
dl 0
loc 296
rs 8.2608
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A write() 0 17 2
F convert() 0 83 23
A columnType() 0 4 2
B compile() 0 45 5
B hasDefaults() 0 13 5
A unsetData() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like DbMigrations 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 DbMigrations, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Elimuswift\DbExporter;
4
5
use Config;
6
use File;
7
use Illuminate\Support\Str;
8
use Elimuswift\DbExporter\Exceptions\InvalidDatabaseException;
9
10
class DbMigrations extends DbExporter
11
{
12
    /**
13
     * Column data types.
14
     *
15
     * @var string
16
     **/
17
    protected $columns = [
18
                            'int' => 'integer',
19
                            'smallint' => 'smallInteger',
20
                            'bigint' => 'bigInteger',
21
                            'char ' => 'string',
22
                            'varchar' => 'string',
23
                            'float' => 'float',
24
                            'double' => 'double',
25
                            'decimal' => 'decimal',
26
                            'tinyint' => 'tinyInteger',
27
                            'date' => 'date',
28
                            'timestamp' => 'timestamp',
29
                            'datetime' => 'dateTime',
30
                            'longtext' => 'longText',
31
                            'mediumtext' => 'mediumText',
32
                            'text' => 'text',
33
                            'longblob' => 'binary',
34
                            'blob' => 'binary',
35
                            'enum' => 'enum',
36
                            'char' => 'char ',
37
                            'geometry' => 'geometry',
38
                            'time' => 'time',
39
                            'point' => 'point',
40
                            'polygon' => 'polygon',
41
                            'multipolygon' => 'muliPolygon',
42
                            'multilinestring' => 'multiLineString',
43
                            'mulitpoint' => 'multiPoint',
44
                            'mediumint' => 'mediumInteger',
45
                            'mac' => 'macAddress',
46
                            'json' => 'json',
47
                            'linestring' => 'lineString',
48
                            'geometrycollection' => 'geometryCollection',
49
                            'bool' => 'boolean',
50
                            'year' => 'year',
51
                            ];
52
    /**
53
     * Primary key column types.
54
     *
55
     * @var array
56
     **/
57
    protected $primaryKeys = [
58
                        'bigint' => 'bigIncrements',
59
                        'int' => 'increments',
60
    ];
61
62
    protected $schema;
63
64
    protected $customDb = false;
65
66
    public static $filePath;
67
68
    protected $primaryKey;
69
70
    protected $defaultLength;
71
72
    protected $methodName;
73
    /**
74
     * File name for migration file.
75
     *
76
     * @var string
77
     */
78
    public $filename;
79
80
    /**
81
     * Set the database name.
82
     *
83
     * @param string $database
84
     * @throw InvalidDatabaseException
85
     */
86
    public function __construct($database)
87
    {
88
        if (empty($database)) {
89
            throw new InvalidDatabaseException('No database set in app/config/database.php');
90
        }
91
92
        $this->database = $database;
93
    }
94
95
    //end __construct()
96
97
    /**
98
     * Write the prepared migration to a file.
99
     */
100
    public function write()
101
    {
102
        // Check if convert method was called before
103
        // If not, call it on default DB
104
        if (!$this->customDb) {
105
            $this->convert();
106
        }
107
108
        $schema = $this->compile();
109
        $absolutePath = Config::get('db-exporter.export_path.migrations');
110
        $this->makePath($absolutePath);
111
        $this->filename = date('Y_m_d_His').'_create_'.$this->database.'_database.php';
112
        static::$filePath = $absolutePath."/{$this->filename}";
113
        file_put_contents(static::$filePath, $schema);
114
115
        return static::$filePath;
116
    }
117
118
    //end write()
119
120
    /**
121
     * Convert the database to migrations
122
     * If none is given, use de DB from condig/database.php.
123
     *
124
     * @param null $database
125
     *
126
     * @return $this
127
     */
128
    public function convert($database = null)
129
    {
130
        if (!is_null($database)) {
131
            $this->database = $database;
132
            $this->customDb = true;
133
        }
134
135
        $tables = $this->getTables();
136
137
        // Loop over the tables
138
        foreach ($tables as $key => $value) {
139
            // Do not export the ignored tables
140
            if (in_array($value['table_name'], static::$ignore)) {
141
                continue;
142
            }
143
144
            $down = "Schema::dropIfExists('{$value['table_name']}');";
145
            $up = "Schema::create('{$value['table_name']}', function(Blueprint $"."table) {\n";
146
147
            $tableDescribes = $this->getTableDescribes($value['table_name']);
148
            // Loop over the tables fields
149
            foreach ($tableDescribes as $values) {
150
                $para = strpos($values->Type, '(');
151
                $type = $para > -1 ? substr($values->Type, 0, $para) : $values->Type;
152
                $nullable = 'NO' == $values->Nullable ? '' : '->nullable()';
153
                $default = empty($values->Default) || 'NULL' == $values->Default ? '' : "->default({$values->Default})";
154
                $default = 'CURRENT_TIMESTAMP' == $values->Default || 'current_timestamp()' == $values->Default ? '->useCurrent()' : $default;
155
                $unsigned = false === strpos($values->Type, 'unsigned') ? '' : '->unsigned()';
156
                $this->hasDefaults($type, $values);
157
                $this->methodName = $this->columnType($type);
158
                if ('PRI' == $values->Key) {
159
                    $this->primaryKey = '->primary()';
160
                    if ($methodName = $this->columnType($values->Data_Type, 'primaryKeys') && 'auto_increment' == $values->Extra) {
0 ignored issues
show
Unused Code introduced by
$methodName is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $methodName = ($this->co...ent' == $values->Extra), Probably Intended Meaning: ($methodName = $this->co...ment' == $values->Extra
Loading history...
161
                        $this->primaryKey = '->autoIncrement()';
162
                    }
163
                }
164
165
                $up .= '                $'."table->{$this->methodName}('{$values->Field}'{$this->defaultLength}){$this->primaryKey}{$nullable}{$default}{$unsigned};\n";
166
                $this->unsetData();
167
            }//end foreach
168
169
            $tableIndexes = (array) $this->getTableIndexes($value['table_name']);
170
            if (!is_null($tableIndexes) && count($tableIndexes)) {
171
                foreach ($tableIndexes as $index) {
172
                    if (Str::endsWith(@$index['Key_name'], '_index')) {
173
                        $up .= '                $'."table->index('".$index['Column_name']."');\n";
174
                    }
175
                }
176
            }
177
178
            $up .= "            });\n\n";
179
            $Constraint = $ConstraintDown = '';
180
            /*
181
                * @var array
182
             */
183
            $tableConstraints = $this->getTableConstraints($value['table_name']);
184
            if (!is_null($tableConstraints) && $tableConstraints->count()) {
0 ignored issues
show
Bug introduced by
The method count cannot be called on $tableConstraints (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
185
                $Constraint = $ConstraintDown = "
186
            Schema::table('{$value['table_name']}', function(Blueprint $"."table) {\n";
187
                $tables = [];
188
                foreach ($tableConstraints as $foreign) {
189
                    if (!in_array($foreign->Field, $tables)) {
190
                        $field = "{$foreign->Table}_{$foreign->Field}_foreign";
191
                        $ConstraintDown .= '                $'."table->dropForeign('".$field."');\n";
192
                        $Constraint .= '                $'."table->foreign('".$foreign->Field."')->references('".$foreign->References."')->on('".$foreign->ON."')->onDelete('".$foreign->onDelete."');\n";
193
                        $tables[$foreign->Field] = $foreign->Field;
194
                    }
195
                }
196
197
                $Constraint .= "            });\n\n";
198
                $ConstraintDown .= "            });\n\n";
199
            }
200
201
            $this->schema[$value['table_name']] = [
202
                                                    'up' => $up,
203
                                                    'constraint' => $Constraint,
204
                                                    'constraint_down' => $ConstraintDown,
205
                                                    'down' => $down,
206
                                                    ];
207
        }//end foreach
208
209
        return $this;
210
    }
211
212
    //end convert()
213
214
    public function columnType($type, $columns = 'columns', $method = '')
215
    {
216
        return array_key_exists($type, $this->{$columns}) ? $this->{$columns}[$type] : $method;
217
    }
218
219
    //end columnType()
220
221
    /**
222
     * Compile the migration into the base migration file
223
     * TODO use a template with seacrh&replace.
224
     *
225
     * @return string
226
     */
227
    protected function compile()
228
    {
229
        $upSchema = '';
230
        $downSchema = '';
231
        $upConstraint = '';
232
        $downConstraint = '';
233
234
        // prevent of failure when no table
235
        if (!is_null($this->schema) && is_array($this->schema)) {
236
            foreach ($this->schema as $name => $values) {
237
                // check again for ignored tables
238
                if (in_array($name, self::$ignore)) {
239
                    continue;
240
                }
241
242
                $upSchema .= "
243
      /**
244
       * Migration schema for table {$name}
245
         * 
246
       */
247
      {$values['up']}";
248
                $upConstraint .= "
249
                {$values['constraint']}";
250
                $downConstraint .= "
251
                {$values['constraint_down']}";
252
253
                $downSchema .= "
254
              {$values['down']}";
255
            }
256
        }//end if
257
258
        // Grab the template
259
        $template = File::get(__DIR__.'/stubs/migration.stub');
260
261
        // Replace the classname
262
        $template = str_replace('{{name}}', 'Create'.ucfirst(Str::camel($this->database)).'Database', $template);
263
264
        // Replace the up and down values
265
        $template = str_replace('{{up}}', $upSchema, $template);
266
        $template = str_replace('{{down}}', $downSchema, $template);
267
        $template = str_replace('{{upCon}}', $upConstraint, $template);
268
        $template = str_replace('{{downCon}}', $downConstraint, $template);
269
270
        return $template;
271
    }
272
273
    /**
274
     * summary.
275
     *
276
     * @author
277
     */
278
    public function hasDefaults($type, $column)
279
    {
280
        if ($hasSize = strpos($column->Type, '(')) {
281
            $values = substr($column->Type, ($hasSize + 1), -1);
282
            if ('enum' == $type) {
283
                $this->defaultLength = ', array('.$values.')';
284
            } elseif (in_array($type, ['char', 'varchar', 'text', 'mediumtext', 'longtext'])) {
285
                $this->defaultLength = ', '.$column->Length;
286
            } elseif (in_array($type, ['double', 'float', 'decimal'])) {
287
                $this->defaultLength = ", $column->Precision, $column->Scale";
288
            }
289
        }
290
    }
291
292
    /**
293
     * summary.
294
     *
295
     * @author
296
     */
297
    protected function unsetData()
298
    {
299
        $this->primaryKey = null;
300
        $this->methodName = null;
301
        $this->defaultLength = null;
302
    }
303
304
    //end compile()
305
}//end class
306