Seeder::generate()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 67
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 46
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 67
rs 8.5559

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 Illuminate\Support\Str;
5
use Prateekkarki\Laragen\Models\LaragenOptions;
6
use Prateekkarki\Laragen\Generators\BaseGenerator;
7
use Prateekkarki\Laragen\Generators\GeneratorInterface;
8
9
class Seeder extends BaseGenerator implements GeneratorInterface
10
{
11
    protected static $initializeFlag = 0;
12
13
    protected $specialTypesToDefinition = [
14
        'title'             => 'realText(20)',
15
        'firstname'         => 'firstname',
16
        'lastname'          => 'lastname',
17
        'name'              => 'name',
18
        'company'           => 'company',
19
        'email'             => 'email',
20
        'streetName'        => 'streetName',
21
        'streetAddress'     => 'streetAddress',
22
        'postcode'          => 'postcode',
23
        'address'           => 'address',
24
        'country'           => 'country',
25
        'dateTime'          => 'dateTime',
26
        'month'             => 'month',
27
        'year'              => 'year',
28
        'url'               => 'url',
29
        'slug'              => 'slug',
30
        'sort'              => 'numberBetween(0,20)',
31
        'short_description' => 'realText(150)',
32
        'long_description'  => 'realText(192)',
33
        'description'       => 'realText(120)',
34
        'content'           => 'realText(192)',
35
    ];
36
37
    protected $typeToDefinition = [
38
        'string'    => 'sentence',
39
        'integer'   => 'randomNumber()',
40
        'text'      => 'realText(250)',
41
        'boolean'   => 'numberBetween(0,1)',
42
        'date'      => 'date',
43
        'datetime'  => 'dateTime',
44
    ];
45
46
    public function generate()
47
    {
48
        $generatedFiles = [];
49
50
        if ($this::$initializeFlag == 0) {
51
            $laragen = LaragenOptions::getInstance();
52
            $modules = $laragen->getModules();
53
            $permissions = [];
54
            $editPermissions = [];
55
            $viewPermissions = [];
56
            foreach ($modules as $module) {
57
                $permissions[] = 'create_'.$module->getModuleName();
58
                $permissions[] = 'view_'.$module->getModuleName();
59
                $permissions[] = 'edit_'.$module->getModuleName();
60
                $permissions[] = 'delete_'.$module->getModuleName();
61
                foreach ($module->getColumns() as $field) {
62
                    $editPermissions[] = 'edit_'.$module->getModuleName().'_'.$field->getColumnKey();
63
                    $viewPermissions[] = 'view_'.$module->getModuleName().'_'.$field->getColumnKey();
64
                }
65
            }
66
            $allPermissions = [];
67
            $allPermissions = array_merge($allPermissions, $permissions, $editPermissions, $viewPermissions);
68
69
            $permissionsCode = '';
70
            foreach ($allPermissions as $permission) {
71
                $permissionsCode .= "Permission::create(['name' => '".$permission."']);".PHP_EOL.$this->getTabs(2);
72
73
            }
74
75
            $permissionSeederTemplate = $this->buildTemplate('common/permissionSeeder', [
76
                '{{permissions}}'     => $permissionsCode,
77
                '{{viewPermissions}}' => implode("', '", $viewPermissions),
78
                '{{editPermissions}}' => implode("', '", $editPermissions),
79
            ]);
80
81
            $fullFilePath = $this->getPath("database/factories/")."RolesAndPermissionsSeeder.php";
82
            file_put_contents($fullFilePath, $permissionSeederTemplate);
83
            $generatedFiles[] = $fullFilePath;
84
85
        }
86
        $factoryTemplate = $this->buildTemplate('common/Factories/Factory', [
87
            '{{modelName}}'      => $this->module->getModelName(),
88
            '{{usedModels}}'     => $this->getUsedModels($this->module->getFilteredColumns(['hasSingleRelation', 'hasPivot'])),
89
            '{{dataDefinition}}' => $this->getDataDefinition($this->module->getFilteredColumns(['general'])),
90
            '{{foreignData}}'    => $this->getForeignData($this->module->getFilteredColumns(['hasSingleRelation']))
91
        ]);
92
93
        $fullFilePath = $this->getPath("database/factories/").$this->module->getModelName()."Factory.php";
94
        file_put_contents($fullFilePath, $factoryTemplate);
95
        $generatedFiles[] = $fullFilePath;
96
97
        foreach ($this->module->getFilteredColumns(['hasPivot']) as $type) {
98
            $typeTemplate = $this->buildTemplate('common/Factories/Factory', [
99
                '{{modelName}}'      => $type->getPivot(),
100
                '{{usedModels}}'     => $this->getUsedModels($type->getFilteredColumns('hasSingleRelation'), $type->getPivot()),
101
                '{{dataDefinition}}' => "",
102
                '{{foreignData}}'    => $this->getForeignData($type->getFilteredColumns('hasSingleRelation'))
103
            ]);
104
105
            $fullFilePath = $this->getPath("database/factories/").Str::singular($type->getPivot())."Factory.php";
106
            file_put_contents($fullFilePath, $typeTemplate);
107
            $generatedFiles[] = $fullFilePath;
108
        }
109
110
        $generatedFiles[] = $this->updateSeeder();
111
112
        return $generatedFiles;
113
    }
114
115
    protected function getUsedModels($types = false, $model = false) {
116
        $namespace = "App\\Models\\";
117
        $model = $model ? $namespace.$model : $namespace.$this->module->getModelName();
118
        $usedModels = "use ".$model.";";
119
120
        $classes = [$model];
121
122
        foreach ($types as $type) {
123
            $model = $type->getRelatedModel();
124
            $class = ($model == 'User') ? config('laragen.options.user_model') : "App\\Models\\".$model;
125
            if (in_array($class, $classes)) {
126
                continue;
127
            }
128
            $classes[] = $class;
129
            $usedModels .= PHP_EOL."use ".$class.";";
130
        }
131
        return $usedModels;
132
    }
133
134
    protected function getDataDefinition($columns) {
135
        $dataDefinition = "";
136
137
        foreach ($columns as $type) {
138
            $specialTypes = array_keys($this->specialTypesToDefinition);
139
            $dataDefinition .= in_array($type->getColumn(), $specialTypes) ?
140
                $this->getTabs(2)."'{$type->getColumn()}'"." => ".'$faker->'.$this->specialTypesToDefinition[$type->getColumn()] : $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 = $this->getPath("database/seeds/")."LaragenSeeder.php";
162
163
        if(self::$initializeFlag++ == 0)
164
            $this->initializeFile($laragenSeederFile, 'common/Seeder');
165
166
        $this->insertIntoFile(
167
            $laragenSeederFile,
168
            "use Illuminate\Database\Seeder;",
169
            "use App\Models\\".$this->module->getModelName().";\n",
170
            false
171
        );
172
173
        $this->insertIntoFile(
174
            $laragenSeederFile,
175
            "\n        // End factories",
176
            "\n".$this->getTabs(2)."factory(".$this->module->getModelName()."::class, ".config('laragen.options.seed_rows').")->create();",
177
            false
178
        );
179
180
        foreach ($this->module->getFilteredColumns(['needsTableInit']) as $type) {
181
182
            $this->insertIntoFile(
183
                $laragenSeederFile,
184
                "use Illuminate\Database\Seeder;",
185
                "use App\Models\\".$type->getPivot().";\n",
186
                false
187
            );
188
189
            $seedData = PHP_EOL.$this->getTabs(2)."if(".$type->getPivot()."::all()->count()==0){";
190
            $seedData .= PHP_EOL.$this->getTabs(3)."DB::table('".$type->getPivotTable()."')->insert([";
191
            foreach ($type->getDbData() as $title) {
192
                $seedData .= PHP_EOL.$this->getTabs(4);
193
                $seedData .= "['title' => '".$title."'],";
194
            }
195
            $seedData .= PHP_EOL.$this->getTabs(3)."]);";
196
            $seedData .= PHP_EOL.$this->getTabs(2)."}";
197
198
            $this->insertIntoFile(
199
                $laragenSeederFile,
200
                $this->getStub('fragments/DatabaseSeederRun'),
201
                $seedData
202
            );
203
        }
204
205
        foreach ($this->module->getFilteredColumns(['hasPivot']) as $type) {
206
207
            $this->insertIntoFile(
208
                $laragenSeederFile,
209
                "use Illuminate\Database\Seeder;",
210
                "use App\Models\\".$type->getPivot().";\n",
211
                false
212
            );
213
214
            $this->insertIntoFile(
215
                $laragenSeederFile,
216
                "\n        // End factories",
217
                "\n".$this->getTabs(2)."factory(".$type->getPivot()."::class, " . ((int) config('laragen.options.seed_rows') * 2) . ")->create();",
218
                false
219
            );
220
        }
221
222
        return $laragenSeederFile;
223
    }
224
}
225