Completed
Pull Request — master (#53)
by
unknown
01:35
created

ModelCommand::getFieldByRuleAsArrayFields()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 4
nop 2
1
<?php namespace Wn\Generators\Commands;
2
3
4
class ModelCommand extends BaseCommand {
5
6
	protected $signature = 'wn:model
7
        {name : Name of the model.}
8
        {--fillable= : the fillable fields.}
9
        {--dates= : date fields.}
10
        {--has-many= : hasMany relationships.}
11
        {--has-one= : hasOne relationships.}
12
        {--belongs-to= : belongsTo relationships.}
13
        {--belongs-to-many= : belongsToMany relationships.}
14
        {--rules= : fields validation rules.}
15
        {--timestamps=true : enables timestamps on the model.}
16
        {--path=app : where to store the model php file.}
17
        {--soft-deletes= : adds SoftDeletes trait to the model.}
18
        {--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}
19
        {--force= : override the existing files}
20
    ';
21
22
	protected $description = 'Generates a model class for a RESTfull resource';
23
24
    public function handle()
25
    {
26
        $name = $this->argument('name');
27
        $path = $this->option('path');
28
29
        $content = $this->getTemplate('model')
30
            ->with([
31
                'name' => $name,
32
                'namespace' => $this->getNamespace(),
33
                'required' => $this->getFieldByRuleAsArrayFields('required'),
34
                'fillable' => $this->getAsArrayFields('fillable'),
35
                'dates' => $this->getAsArrayFields('dates'),
36
                'relations' => $this->getRelations(),
37
                'rules' => $this->getRules(),
38
                'additional' => $this->getAdditional(),
39
                'uses' => $this->getUses()
40
            ])
41
            ->get();
42
43
        $this->save($content, "./{$path}/{$name}.php", "{$name} model");
44
    }
45
46
    protected function getFieldByRuleAsArrayFields($rule, $allowPartialMatch = false)
0 ignored issues
show
Unused Code introduced by
The parameter $allowPartialMatch is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
47
    {
48
        $rules = $this->getRules(false);
49
        $fields = [];
50
                
51
        foreach($rules as $ruleId => $ruleData){
52
            $fieldRules = explode(',', $ruleData['rule']);
53
            
54
            foreach($fieldRules as $fieldRule){
55
                if($fieldRule === $rule || str_contains($fieldRule, $rule)){
56
                    $fields[] = $ruleData['name'];
57
                }
58
            }
59
        }
60
        
61
        return implode(', ', array_map(function($item){
62
            return '"' . $item . '"';
63
        }, $fields));
64
    }
65
66
    protected function getAsArrayFields($arg, $isOption = true)
67
    {
68
    	$arg = ($isOption) ? $this->option($arg) : $this->argument($arg);
69
        if(is_string($arg)){
70
        	$arg = explode(',', $arg);
71
        } else if(! is_array($arg)) {
72
            $arg = [];
73
        }
74
        return implode(', ', array_map(function($item){
75
            return '"' . $item . '"';
76
        }, $arg));
77
    }
78
79
    protected function getNamespace()
80
    {
81
    	return str_replace(' ', '\\', ucwords(str_replace('/', ' ', $this->option('path'))));
82
    }
83
84
    protected function getRelations()
85
    {
86
        $relations = array_merge([],
87
            $this->getRelationsByType('hasOne', 'has-one'),
88
            $this->getRelationsByType('hasMany', 'has-many'),
89
            $this->getRelationsByType('belongsTo', 'belongs-to'),
90
            $this->getRelationsByType('belongsToMany', 'belongs-to-many', true)
91
        );
92
93
        if(empty($relations)){
94
            return "    // Relationships";
95
        }
96
97
        return implode(PHP_EOL, $relations);
98
    }
99
100
    protected function getRelationsByType($type, $option, $withTimestamps = false)
101
    {
102
        $relations = [];
103
        $option = $this->option($option);
104
        if($option){
105
106
            $items = $this->getArgumentParser('relations')->parse($option);
107
108
            $template = ($withTimestamps) ? 'model/relation-with-timestamps' : 'model/relation';
109
            $template = $this->getTemplate($template);
110
            foreach ($items as $item) {
111
                $item['type'] = $type;
112
                if(! $item['model']){
113
                    $item['model'] = $this->getNamespace() . '\\' . ucwords(str_singular($item['name']));
114
                } else if(strpos($item['model'], '\\') === false ){
115
                    $item['model'] = $this->getNamespace() . '\\' . $item['model'];
116
                }
117
                $relations[] = $template->with($item)->get();
118
            }
119
        }
120
        return $relations;
121
    }
122
123
    protected function getRules($inTemplate = true)
124
    {
125
        $rules = $this->option('rules');
126
        if(! $rules){
127
            return "        // Validation rules";
128
        }
129
        $items = $rules;
130
        if(! $this->option('parsed')){
131
            $items = $this->getArgumentParser('rules')->parse($rules);
132
        }
133
        $model = $this->argument('name');
134
        $rules = [];
135
        $template = $this->getTemplate('model/rule');
136
        foreach ($items as $item) {
137
            $rules[] = $template->with(array_merge(
138
                $item,
139
                [ 'model' => $model ]
140
            ))->get();
141
        }
142
143
        return $inTemplate ? implode(PHP_EOL, $rules) : $items;
144
    }
145
146
    protected function getAdditional()
147
    {
148
        return $this->option('timestamps') == 'false'
149
            ? "    public \$timestamps = false;" . PHP_EOL . PHP_EOL
150
            : '';
151
    }
152
153
    protected function getUses()
154
    {
155
        return $this->option('soft-deletes') == 'true'
156
            ? '    use \Illuminate\Database\Eloquent\SoftDeletes;' . PHP_EOL . PHP_EOL
157
            : '';
158
    }
159
160
}
161