Passed
Branch master (d88b3b)
by Prateek
03:56
created

Seeder::updateSeeder()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 60
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 40
c 0
b 0
f 0
nc 12
nop 0
dl 0
loc 60
rs 8.9688

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
2
namespace Prateekkarki\Laragen\Generators\Common;
3
4
use Prateekkarki\Laragen\Generators\BaseGenerator;
5
use Prateekkarki\Laragen\Generators\GeneratorInterface;
6
use Illuminate\Support\Str;
7
8
class Seeder extends BaseGenerator implements GeneratorInterface
9
{
10
    protected static $initializeFlag = 0;
11
12
    protected $specialTypesToDefinition = [
13
        'title'             => 'realText(20)',
14
        'firstname'         => 'firstname',
15
        'lastname'          => 'lastname',
16
        'name'              => 'name',
17
        'company'           => 'company',
18
        'email'             => 'email',
19
        'streetName'        => 'streetName',
20
        'streetAddress'     => 'streetAddress',
21
        'postcode'          => 'postcode',
22
        'address'           => 'address',
23
        'country'           => 'country',
24
        'dateTime'          => 'dateTime',
25
        'month'             => 'month',
26
        'year'              => 'year',
27
        'url'               => 'url',
28
        'slug'              => 'slug',
29
        'sort'              => 'numberBetween(0,20)',
30
        'short_description' => 'realText(150)',
31
        'long_description'  => 'realText(192)',
32
        'description'       => 'realText(120)',
33
        'content'           => 'realText(192)',
34
    ];
35
36
    protected $typeToDefinition = [
37
        'string'    => 'sentence',
38
        'integer'   => 'randomNumber()',
39
        'text'      => 'realText(250)',
40
        'boolean'   => 'numberBetween(0,1)',
41
        'date'      => 'date',
42
        'datetime'  => 'dateTime',
43
    ];
44
45
    public function generate()
46
    {
47
        $generatedFiles = [];
48
49
        if($this::$initializeFlag == 0){
50
            $laragen = app('laragen');
51
            $modules = $laragen->getModules();
0 ignored issues
show
Bug introduced by
The method getModules() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
            /** @scrutinizer ignore-call */ 
52
            $modules = $laragen->getModules();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
52
            $permissions = [];
53
            $editPermissions = [];
54
            $viewPermissions = [];
55
            foreach ($modules as $module) {
56
                $permissions[] = 'create_'.$module->getModuleName();
57
                $permissions[] = 'view_'.$module->getModuleName();
58
                $permissions[] = 'edit_'.$module->getModuleName();
59
                $permissions[] = 'delete_'.$module->getModuleName();
60
                foreach ($module->getColumns() as $field) {
61
                    $editPermissions[] = 'edit_'.$module->getModuleName().'_'.$field->getColumnKey();
62
                    $viewPermissions[] = 'view_'.$module->getModuleName().'_'.$field->getColumnKey();
63
                }
64
            }
65
            $allPermissions = [];
66
            $allPermissions = array_merge($allPermissions, $permissions, $editPermissions, $viewPermissions);
67
68
            $permissionsCode = '';
69
            foreach ($allPermissions as $permission) {
70
                $permissionsCode .= "Permission::create(['name' => '". $permission ."']);" . PHP_EOL. $this->getTabs(2);
71
72
            }
73
74
            $permissionSeederTemplate = $this->buildTemplate('common/permissionSeeder', [
75
                '{{permissions}}'     => $permissionsCode,
76
                '{{viewPermissions}}' => implode("', '", $viewPermissions),
77
                '{{editPermissions}}' => implode("', '", $editPermissions),
78
            ]);
79
80
            $fullFilePath = $this->getPath("database/factories/")."RolesAndPermissionsSeeder.php";
81
            file_put_contents($fullFilePath, $permissionSeederTemplate);
82
            $generatedFiles[] = $fullFilePath;
83
84
        }
85
        $factoryTemplate = $this->buildTemplate('common/Factories/Factory', [
86
            '{{modelName}}'      => $this->module->getModelName(),
87
            '{{usedModels}}'     => $this->getUsedModels($this->module->getFilteredColumns(['hasSingleRelation', 'hasPivot'])),
88
            '{{dataDefinition}}' => $this->getDataDefinition($this->module->getFilteredColumns(['general'])),
89
            '{{foreignData}}'    => $this->getForeignData($this->module->getFilteredColumns(['hasSingleRelation']))
90
        ]);
91
92
        $fullFilePath = $this->getPath("database/factories/").$this->module->getModelName()."Factory.php";
93
        file_put_contents($fullFilePath, $factoryTemplate);
94
        $generatedFiles[] = $fullFilePath;
95
96
        foreach($this->module->getFilteredColumns(['hasPivot']) as $type){
97
            $typeTemplate = $this->buildTemplate('common/Factories/Factory', [
98
                '{{modelName}}'      => $type->getPivot(),
99
                '{{usedModels}}'     => $this->getUsedModels($type->getFilteredColumns('hasSingleRelation'), $type->getPivot()),
100
                '{{dataDefinition}}' => $this->getDataDefinition($type->getFilteredColumns('general')),
101
                '{{foreignData}}'    => $this->getForeignData($type->getFilteredColumns('hasSingleRelation'))
102
            ]);
103
            
104
            $fullFilePath = $this->getPath("database/factories/").Str::singular($type->getPivot())."Factory.php";
105
            file_put_contents($fullFilePath, $typeTemplate);
106
            $generatedFiles[] = $fullFilePath;
107
        }
108
        
109
        $generatedFiles[] = $this->updateSeeder();
110
        
111
        return $generatedFiles;         
112
    }
113
114
    protected function getUsedModels($types = false, $model = false) {
115
        $namespace = "App\\Models\\";
116
        $model = $model ? $namespace.$model : $namespace.$this->module->getModelName();
117
        $usedModels = "use ".$model.";";
118
119
        $classes = [$model];
120
121
        foreach($types as $type){
122
            $model = $type->getRelatedModel();
123
            $class = ($model == 'User') ? config('laragen.options.user_model') : "App\\Models\\".$model;
124
            if(in_array($class, $classes)){
125
                continue;
126
            }
127
            $classes[] = $class;
128
            $usedModels .= PHP_EOL."use ".$class.";";
129
        }
130
        return $usedModels;
131
    }
132
133
    protected function getDataDefinition($columns) {
134
        $dataDefinition = "";
135
136
        foreach ($columns as $type) {
137
            $specialTypes = array_keys($this->specialTypesToDefinition);
138
            $dataDefinition .= in_array($type->getColumn(), $specialTypes) ? 
139
                $this->getTabs(2)."'{$type->getColumn()}'"." => ".'$faker->'.$this->specialTypesToDefinition[$type->getColumn()] : 
140
                $this->getTabs(2)."'{$type->getColumn()}'"." => ".'$faker->'.$this->typeToDefinition[$type->getDataType()];
141
            $dataDefinition .= ",".PHP_EOL;
142
        }
143
        return $dataDefinition;
144
    }
145
146
    protected function getForeignData($types) {
147
        $foreignData = "";
148
149
        foreach($types as $type){
150
            if($type->hasSelfParent()) continue;
151
            $foreignData .= $this->buildTemplate('common/Factories/fragments/options', [
152
                '{{parent}}'      => $type->getColumnKey(),
153
                '{{parentModel}}' => $type->getRelatedModel()
154
            ]);
155
            $foreignData .= ",".PHP_EOL;
156
        }
157
        return $foreignData;
158
    }
159
160
    protected function updateSeeder() {
161
        $laragenSeederFile = (self::$initializeFlag++ == 0) ? $this->initializeFile($this->getPath("database/seeds/")."LaragenSeeder.php", 'common/Seeder') : $this->getPath("database/seeds/")."LaragenSeeder.php";
162
163
        $this->insertIntoFile(
164
            $laragenSeederFile,
165
            "use Illuminate\Database\Seeder;",
166
            "use App\Models\\".$this->module->getModelName().";\n",
167
            false
168
        );
169
170
        $this->insertIntoFile(
171
            $laragenSeederFile,
172
            "\n        // End factories",
173
            "\n".$this->getTabs(2)."factory(".$this->module->getModelName()."::class, ".config('laragen.options.seed_rows').")->create();",
174
            false
175
        );
176
177
        foreach($this->module->getFilteredColumns(['needsTableInit']) as $type){
178
            
179
            $this->insertIntoFile(
180
                $laragenSeederFile,
181
                "use Illuminate\Database\Seeder;",
182
                "use App\Models\\".$type->getPivot().";\n",
183
                false
184
            );
185
186
            $seedData = PHP_EOL.$this->getTabs(2). "if(".$type->getPivot()."::all()->count()==0){";
187
            $seedData .= PHP_EOL.$this->getTabs(3). "DB::table('".$type->getPivotTable()."')->insert([";
188
            foreach($type->getDbData() as $title){
189
                $seedData .= PHP_EOL.$this->getTabs(4);
190
                $seedData .= "['title' => '" . $title . "'],";
191
            }
192
            $seedData .=  PHP_EOL.$this->getTabs(3). "]);";
193
            $seedData .=  PHP_EOL.$this->getTabs(2). "}";
194
195
            $this->insertIntoFile(
196
                $laragenSeederFile,
197
                $this->getStub('fragments/DatabaseSeederRun'),
198
                $seedData
199
            );
200
        }
201
202
        foreach($this->module->getFilteredColumns(['hasPivot']) as $type){
203
            
204
            $this->insertIntoFile(
205
                $laragenSeederFile,
206
                "use Illuminate\Database\Seeder;",
207
                "use App\Models\\".$type->getPivot().";\n",
208
                false
209
            );
210
211
            $this->insertIntoFile(
212
                $laragenSeederFile,
213
                "\n        // End factories",
214
                "\n".$this->getTabs(2)."factory(".$type->getPivot()."::class, ".(int)config('laragen.options.seed_rows') * 2 .")->create();",
215
                false
216
            );
217
        }
218
219
        return $laragenSeederFile;
220
    }
221
}
222