ResourcesCommand::handle()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 9.0036
c 0
b 0
f 0
cc 4
nc 6
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace Wn\Generators\Commands;
2
3
use InvalidArgumentException;
4
use Symfony\Component\Yaml\Yaml;
5
use Illuminate\Support\Str;
6
7
class ResourcesCommand extends BaseCommand {
8
9
    protected $signature = 'wn:resources
10
        {file : Path to the file containing resources declarations}
11
        {--path=app : where to store the model files.}
12
        {--force= : override the existing files}
13
        {--laravel= : Use Laravel style route definitions}
14
15
    ';
16
17
    protected $description = 'Generates multiple resources from a file';
18
19
    protected $pivotTables = [];
20
21
    public function handle()
22
    {
23
        $content = $this->fs->get($this->argument('file'));
0 ignored issues
show
Bug introduced by
It seems like $this->argument('file') targeting Illuminate\Console\Command::argument() can also be of type array; however, Illuminate\Filesystem\Filesystem::get() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
24
        $content = Yaml::parse($content);
25
26
        $modelIndex = 0;
27
        foreach ($content as $model => $i){
28
            $i = $this->getResourceParams($model, $i);
29
            $migrationName = 'Create' .  ucwords(Str::plural($i['name']));
30
            $migrationFile = date('Y_m_d_His') . '-' . str_pad($modelIndex , 3, 0, STR_PAD_LEFT) . '_' . Str::snake($migrationName) . '_table';
31
            
32
            $options = [
33
                'name' => $i['name'],
34
                'fields' => $i['fields'],
35
                '--add' => $i['add'],
36
                '--has-many' => $i['hasMany'],
37
                '--has-one' => $i['hasOne'],
38
                '--belongs-to' => $i['belongsTo'],
39
                '--belongs-to-many' => $i['belongsToMany'],
40
                '--path' => $this->option('path'),
41
                '--force' => $this->option('force'),
42
                '--migration-file' => $migrationFile
43
            ];
44
            if ($this->option('laravel')) {
45
                $options['--laravel'] = true;
46
            }
47
48
            $this->call('wn:resource', $options);
49
            $modelIndex++;
50
        }
51
52
        // $this->call('migrate'); // actually needed for pivot seeders !
53
54
        $this->pivotTables = array_map(
55
            'unserialize',
56
            array_unique(array_map('serialize', $this->pivotTables))
57
        );
58
59
        foreach ($this->pivotTables as $tables) {
60
            $this->call('wn:pivot-table', [
61
                'model1' => $tables[0],
62
                'model2' => $tables[1],
63
                '--force' => $this->option('force')
64
            ]);
65
66
            // $this->call('wn:pivot-seeder', [
67
            //     'model1' => $tables[0],
68
            //     'model2' => $tables[1],
69
            //     '--force' => $this->option('force')
70
            // ]);
71
        }
72
73
        $this->call('migrate');
74
    }
75
76
    protected function getResourceParams($modelName, $i)
77
    {
78
       $i['name'] = Str::snake($modelName);
79
80
        foreach(['hasMany', 'hasOne', 'add', 'belongsTo', 'belongsToMany'] as $relation){
81
            if(isset($i[$relation])){
82
                $i[$relation] = $this->convertArray($i[$relation], ' ', ',');
83
            } else {
84
                $i[$relation] = false;
85
            }
86
        }
87
88
        if($i['belongsToMany']){
89
            $relations = $this->getArgumentParser('relations')->parse($i['belongsToMany']);
90
            foreach ($relations as $relation){
91
                $table = '';
0 ignored issues
show
Unused Code introduced by
$table 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...
92
93
                if(! $relation['model']){
94
                    $table = Str::snake($relation['name']);
95
                } else {
96
                    $names = array_reverse(explode("\\", $relation['model']));
97
                    $table = Str::snake($names[0]);
98
                }
99
100
                $tables = [ Str::singular($table), $i['name'] ];
101
                sort($tables);
102
                $this->pivotTables[] = $tables;
103
            }
104
        }
105
106
        $fields = [];
107
        foreach($i['fields'] as $name => $value) {
0 ignored issues
show
Bug introduced by
The expression $i['fields'] of type string|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
108
            $value['name'] = $name;
109
            $fields[] = $this->serializeField($value);
110
        }
111
        $i['fields'] = implode(' ', $fields);
112
113
        return $i;
114
    }
115
116
    protected function serializeField($field)
117
    {
118
        $name = $field['name'];
119
        $schema = $this->convertArray(Str::replace(':', '.', $field['schema']), ' ', ':');
0 ignored issues
show
Bug introduced by
The method replace() does not exist on Illuminate\Support\Str. Did you maybe mean replaceArray()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
120
        $rules = (isset($field['rules'])) ? trim($field['rules']) : '';
121
        // Replace space by comma
122
        $rules = Str::replace(' ', ',', $rules);
0 ignored issues
show
Bug introduced by
The method replace() does not exist on Illuminate\Support\Str. Did you maybe mean replaceArray()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
123
124
        $tags = $this->convertArray($field['tags'], ' ', ',');
125
126
        $string = "{$name};{$schema};{$rules};{$tags}";
127
128
        if(isset($field['factory']) && !empty($field['factory'])){
129
            $string .= ';' . $field['factory'];
130
        }
131
132
        return $string;
133
    }
134
135
    protected function convertArray($list, $old, $new)
136
    {
137
        return implode($new, array_filter(explode($old, $list), function($item){
138
            return !empty($item);
139
        }));
140
    }
141
142
}
143