Completed
Pull Request — master (#66)
by
unknown
01:44
created

MigrationCommand::buildParameters()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4222
c 0
b 0
f 0
cc 5
nc 4
nop 3
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(camel_case($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 or null; however, camel_case() 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 = snake_case($name);
25
26
        $file = $this->option('file');
27
        if (! $file) {
28
            $file = date('Y_m_d_His_') . $snakeName . '_table';
29
            $this->deleteOldMigration($snakeName);
30
        } else {
31
            $this->deleteOldMigration($file);
32
        }
33
34
        $content = $this->getTemplate('migration')
35
            ->with([
36
                'table' => $table,
37
                'name' => $name,
38
                'schema' => $this->getSchema($this->option('schema')),
39
                'additionals' => $this->getAdditionals($this->option('add')),
40
                'constraints' => $this->getConstraints($this->option('keys'))
41
            ])
42
            ->get();
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
    protected function getSchema($schema)
59
    {
60
        return $this->buildParameters($this->parseValue($schema, 'schema'), "// Schema declaration", [$this, 'getFieldDeclaration']);
61
    }
62
63
    protected function getAdditionals($additionals)
64
    {
65
        if (empty($additionals)) {
66
            return '';
67
        }
68
69
        $additionals = explode(',', $additionals);
70
        $lines = [];
71
        foreach ($additionals as $add) {
72
            $add = trim($add);
73
            $lines[] = $this->spaces(12) . "\$table->{$add}();";
74
        }
75
76
        return implode(PHP_EOL, $lines);
77
    }
78
79
    protected function getFieldDeclaration($parts)
80
    {
81
        $name = $parts[0]['name'];
82
        $parts[1]['args'] = array_merge(["'{$name}'"], $parts[1]['args']);
83
        unset($parts[0]);
84
        $parts = array_map(function($part){
85
            return '->' . $part['name'] . '(' . implode(', ', $part['args']) . ')';
86
        }, $parts);
87
        return "            \$table" . implode('', $parts) . ';';
88
    }
89
90
    protected function getConstraints($keys)
91
    {
92
        return $this->buildParameters($this->parseValue($keys, 'foreign-keys'), "// Constraints declaration", [$this, 'getConstraintDeclaration']);
93
    }
94
95
    protected function buildParameters($items, $emptyPlaceholder, $callback = null) {
96
        if ($items === false) {
97
            return $this->spaces(12) . $emptyPlaceholder;
98
        }
99
100
        $parameters = [];
101
        foreach ($items as $item) {
102
            if (!empty($callback) && is_callable($callback)) {
103
                $parameters[] = call_user_func($callback, $item);
104
            } else {
105
                $parameters[] = $item;
106
            }
107
        }
108
109
        return implode(PHP_EOL, $parameters);
110
    }
111
112
    protected function getConstraintDeclaration($key)
113
    {
114
        if(! $key['column']){
115
            $key['column'] = 'id';
116
        }
117
        if(! $key['table']){
118
            $key['table'] = substr($key['name'], 0, count($key['name']) - 4);
119
        }
120
121
        $constraint = $this->getTemplate('migration/foreign-key')
122
            ->with([
123
                'name' => $key['name'],
124
                'table' => snake_case(str_plural($key['table'])),
125
                'column' => $key['column']
126
            ])
127
            ->get();
128
129 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...
130
            $constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
131
                    ->with([
132
                        'event' => 'Delete',
133
                        'action' => $key['on_delete']
134
                    ])
135
                    ->get();
136
        }
137
138 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...
139
            $constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
140
                    ->with([
141
                        'event' => 'Update',
142
                        'action' => $key['on_update']
143
                    ])
144
                    ->get();
145
        }
146
147
        return $constraint . ';';
148
    }
149
150
}
151