ResourceCommand::parseFields()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 9.488
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php namespace Wn\Generators\Commands;
2
3
4
use InvalidArgumentException;
5
use Illuminate\Support\Str;
6
7
class ResourceCommand extends BaseCommand {
8
9
    protected $signature = 'wn:resource
10
        {name : Name of the resource.}
11
        {fields : fields description.}
12
        {--has-many= : hasMany relationships.}
13
        {--has-one= : hasOne relationships.}
14
        {--belongs-to= : belongsTo relationships.}
15
        {--belongs-to-many= : belongsToMany relationships.}
16
        {--images= : images associated with resource}
17
        {--migration-file= : the migration file name.}
18
        {--add= : specifies additional columns like timestamps, softDeletes, rememberToken and nullableTimestamps.}
19
        {--path=app : where to store the model file.}
20
        {--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}
21
        {--force= : override the existing files}
22
        {--laravel= : Use Laravel style route definitions}
23
    ';
24
25
    protected $description = 'Generates a model, migration, controller and routes for RESTful resource';
26
27
    protected $fields;
28
29
    public function handle()
30
    {
31
        $this->parseFields();
32
33
        $resourceName = $this->argument('name');
34
        $modelName = ucwords(Str::camel($resourceName));
0 ignored issues
show
Bug introduced by
It seems like $resourceName defined by $this->argument('name') on line 33 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...
35
        $tableName = Str::plural($resourceName);
0 ignored issues
show
Bug introduced by
It seems like $resourceName defined by $this->argument('name') on line 33 can also be of type array; however, Illuminate\Support\Str::plural() 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...
36
37
        // generating the model
38
        $this->call('wn:model', [
39
            'name' => $modelName,
40
            '--fillable' => $this->fieldsHavingTag('fillable'),
41
            '--guarded' => $this->fieldsHavingTag('guarded'),
42
            '--dates' => $this->fieldsHavingTag('date'),
43
            '--has-many' => $this->option('has-many'),
44
            '--has-one' => $this->option('has-one'),
45
            '--belongs-to' => $this->option('belongs-to'),
46
            '--belongs-to-many' => $this->option('belongs-to-many'),
47
            '--images' => $this->option('images'),
48
            '--rules' => $this->rules(),
49
            '--path' => $this->option('path'),
50
            '--force' => $this->option('force'),
51
            '--soft-deletes' => $this->hasSoftDeletes() ? 'true' : 'false',
52
            '--parsed' => true
53
        ]);
54
55
        // generating the migration
56
        $this->call('wn:migration', [
57
            'table' => $tableName,
58
            '--schema' => $this->schema(),
59
            '--keys' => $this->migrationKeys(),
60
            '--file' => $this->option('migration-file'),
61
            '--force' => $this->option('force'),
62
            '--add' => $this->option('add'),
63
            '--parsed' => true
64
        ]);
65
66
        // generating REST actions trait if doesn't exist
67
        if(! $this->fs->exists('./app/Http/Controllers/RESTActions.php')){
68
            $this->call('wn:controller:rest-actions');
69
        }
70
        // generating the controller and routes
71
        $controllerOptions = [
72
            'model' => $modelName,
73
            '--force' => $this->option('force'),
74
            '--no-routes' => false,
75
        ];
76
        if ($this->option('laravel')) {
77
            $controllerOptions['--laravel'] = true;
78
        }
79
        $this->call('wn:controller', $controllerOptions);
80
81
        // generating model factory
82
        $this->call('wn:factory', [
83
            'model' => 'App\\' . $modelName,
84
            '--fields' => $this->factoryFields(),
85
            '--force' => $this->option('force'),
86
            '--parsed' => true
87
        ]);
88
89
        // generating database seeder
90
        // $this->call('wn:seeder', [
91
        //     'model' => 'App\\' . $modelName
92
        // ]);
93
94
    }
95
96
    protected function parseFields()
97
    {
98
        $fields = $this->argument('fields');
99
        if($this->option('parsed')){
100
            $this->fields = $fields;
101
        } else {
102
            if(! $fields){
103
                $this->fields = [];
104
            } else {
105
                $this->fields = $this->getArgumentParser('fields')
106
                    ->parse($fields);
107
            }
108
            $this->fields = array_merge($this->fields, array_map(function($name) {
109
                return [
110
                    'name' => $name,
111
                    'schema' => [
112
                        ['name' => 'integer', 'args' => []],
113
                        ['name' => 'unsigned', 'args' => []]
114
                    ],
115
                    'rules' => 'required|numeric',
116
                    'tags' => ['fillable', 'key'],
117
                    'factory' => 'key'
118
                ];
119
            }, $this->foreignKeys()));
120
        }
121
122
    }
123
124
    protected function fieldsHavingTag($tag)
125
    {
126
        return array_map(function($field){
127
            return $field['name'];
128
        }, array_filter($this->fields, function($field) use($tag){
129
            return in_array($tag, $field['tags']);
130
        }));
131
    }
132
133 View Code Duplication
    protected function rules()
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...
134
    {
135
        return array_map(function($field){
136
            return [
137
                'name' => $field['name'],
138
                'rule' => $field['rules']
139
            ];
140
        }, array_filter($this->fields, function($field){
141
            return !empty($field['rules']);
142
        }));
143
    }
144
145
    protected function schema()
146
    {
147
        return array_map(function($field){
148
            return array_merge([[
149
                'name' => $field['name'],
150
                'args' => []
151
            ]], $field['schema']);
152
        }, $this->fields);
153
    }
154
155
    protected function foreignKeys()
156
    {
157
        $belongsTo = $this->option('belongs-to');
158
        if(! $belongsTo) {
159
            return [];
160
        }
161
        $relations = $this->getArgumentParser('relations')->parse($belongsTo);
162
        return array_map(function($relation){
163
            $name = $relation['model'] ? $relation['model'] : $relation['name'];
164
            $index = strrpos($name, "\\");
165
            if($index) {
166
                $name = substr($name, $index + 1);
167
            }
168
            return Str::snake(Str::singular($name)) . '_id';
169
        }, $relations);
170
    }
171
172
    protected function migrationKeys() {
173
        return array_map(function($name) {
174
            return [
175
                'name' => $name,
176
                'column' => '',
177
                'table' => '',
178
                'on_delete' => '',
179
                'on_update' => ''
180
            ];
181
        }, $this->foreignKeys());
182
    }
183
184 View Code Duplication
    protected function factoryFields()
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...
185
    {
186
        return array_map(function($field){
187
            return [
188
                'name' => $field['name'],
189
                'type' => $field['factory']
190
            ];
191
        }, array_filter($this->fields, function($field){
192
            return isset($field['factory']) && $field['factory'];
193
        }));
194
    }
195
196
    protected function hasTimestamps()
197
    {
198
        $additionals = explode(',', $this->option('add'));
199
        return in_array('nullableTimestamps', $additionals)
200
            || in_array('timestamps', $additionals)
201
            || in_array('timestampsTz', $additionals);
202
    }
203
204
    protected function hasSoftDeletes()
205
    {
206
        $additionals = explode(',', $this->option('add'));
207
        return in_array('softDeletes', $additionals);
208
    }
209
210
}
211