MigrationCommand::deleteOldMigration()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php namespace Wn\Generators\Commands;
2
3
4
class MigrationCommand extends BaseCommand {
5
6
    protected $signature = 'wn:migration
7
        {table : The table name.}
8
        {--schema= : the schema.}
9
        {--add= : specifies additional columns like timestamps, softDeletes, rememberToken and nullableTimestamps.}
10
        {--keys= : foreign keys.}
11
        {--file= : name of the migration file (to use only for testing purpose).}
12
        {--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options}
13
        {--force= : override the existing files}
14
    ';
15
    // {action : One of create, add, remove or drop options.}
16
    // The action is only create for the moment
17
18
    protected $description = 'Generates a migration to create a table with schema';
19
20
    public function handle()
21
    {
22
        $table = $this->argument('table');
23
        $name = 'Create' . ucwords(\Illuminate\Support\Str::camel($table));
0 ignored issues
show
Bug introduced by
It seems like $table defined by $this->argument('table') on line 22 can also be of type array; however, Illuminate\Support\Str::camel() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
24
        $snakeName = \Illuminate\Support\Str::snake($name);
25
26
        $content = $this->getTemplate('migration')
27
            ->with([
28
                'table' => $table,
29
                'name' => $name,
30
                'schema' => $this->getSchema(),
31
                'additionals' => $this->getAdditionals(),
32
                'constraints' => $this->getConstraints()
33
            ])
34
            ->get();
35
36
        $file = $this->option('file');
37
        if(! $file){
38
            $file = date('Y_m_d_His_') . $snakeName . '_table';
39
            $this->deleteOldMigration($snakeName);
40
        }else{
41
            $this->deleteOldMigration($file);
42
        }
43
44
        $this->save($content, "./database/migrations/{$file}.php", "{$table} migration");
45
    }
46
47
    protected function deleteOldMigration($fileName)
48
    {
49
        foreach (new \DirectoryIterator("./database/migrations/") as $fileInfo){
50
            if($fileInfo->isDot()) continue;
51
52
            if(strpos($fileInfo->getFilename(), $fileName) !== FALSE){
53
                unlink($fileInfo->getPathname());
54
            }
55
        }
56
    }
57
58 View Code Duplication
    protected function getSchema()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
59
    {
60
        $schema = $this->option('schema');
61
        if(! $schema){
62
            return $this->spaces(12) . "// Schema declaration";
63
        }
64
65
        $items = $schema;
66
        if( ! $this->option('parsed')){
67
            $items = $this->getArgumentParser('schema')->parse($schema);
68
        }
69
70
        $fields = [];
71
        foreach ($items as $item) {
72
            $fields[] = $this->getFieldDeclaration($item);
73
        }
74
75
        return implode(PHP_EOL, $fields);
76
    }
77
78
    protected function getAdditionals()
79
    {
80
        $additionals = $this->option('add');
81
        if (empty($additionals)) {
82
            return '';
83
        }
84
85
        $additionals = explode(',', $additionals);
86
        $lines = [];
87
        foreach ($additionals as $add) {
88
            $add = trim($add);
89
            $lines[] = $this->spaces(12) . "\$table->{$add}();";
90
        }
91
92
        return implode(PHP_EOL, $lines);
93
    }
94
95
    protected function getFieldDeclaration($parts)
96
    {
97
        $name = $parts[0]['name'];
98
        $parts[1]['args'] = array_merge(["'{$name}'"], $parts[1]['args']);
99
        unset($parts[0]);
100
        $parts = array_map(function($part){
101
            return '->' . $part['name'] . '(' . implode(', ', $part['args']) . ')';
102
        }, $parts);
103
        return "            \$table" . implode('', $parts) . ';';
104
    }
105
106 View Code Duplication
    protected function getConstraints()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
107
    {
108
        $keys = $this->option('keys');
109
        if(! $keys){
110
            return $this->spaces(12) . "// Constraints declaration";
111
        }
112
113
        $items = $keys;
114
        if(! $this->option('parsed')){
115
            $items = $this->getArgumentParser('foreign-keys')->parse($keys);
116
        }
117
118
        $constraints = [];
119
        foreach ($items as $item) {
120
            $constraints[] = $this->getConstraintDeclaration($item);
121
        }
122
123
        return implode(PHP_EOL, $constraints);
124
    }
125
126
    protected function getConstraintDeclaration($key)
127
    {
128
        if(! $key['column']){
129
            $key['column'] = 'id';
130
        }
131
        if(! $key['table']){
132
            $key['table'] = \Illuminate\Support\Str::plural(substr($key['name'], 0, strlen($key['name']) - 3));
133
        }
134
135
        $constraint = $this->getTemplate('migration/foreign-key')
136
            ->with([
137
                'name' => $key['name'],
138
                'table' => $key['table'],
139
                'column' => $key['column']
140
            ])
141
            ->get();
142
143 View Code Duplication
        if($key['on_delete']){
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...
144
            $constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
145
                    ->with([
146
                        'event' => 'Delete',
147
                        'action' => $key['on_delete']
148
                    ])
149
                    ->get();
150
        }
151
152 View Code Duplication
        if($key['on_update']){
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...
153
            $constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
154
                    ->with([
155
                        'event' => 'Update',
156
                        'action' => $key['on_update']
157
                    ])
158
                    ->get();
159
        }
160
161
        return $constraint . ';';
162
    }
163
164
}
165