Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 15 | class DatabaseModuleGenerator extends ModuleGenerator |
||
| 16 | { |
||
| 17 | protected $silentOutput = false; |
||
| 18 | |||
| 19 | public function setSilentOutput($bool = true) |
||
| 20 | { |
||
| 21 | $this->silentOutput = $bool; |
||
| 22 | |||
| 23 | return $this; |
||
| 24 | } |
||
| 25 | |||
| 26 | /** |
||
| 27 | * Generate the module. |
||
| 28 | */ |
||
| 29 | public function generate(): int |
||
| 30 | { |
||
| 31 | return DB::transaction(function () { |
||
| 32 | $name = $this->getName(); |
||
| 33 | |||
| 34 | View Code Duplication | if ($this->module->has($name)) { |
|
|
|
|||
| 35 | if ($this->force) { |
||
| 36 | $this->module->delete($name); |
||
| 37 | } else { |
||
| 38 | if (!$this->silentOutput) { |
||
| 39 | $this->console->info("Module [{$name}] already exist!"); |
||
| 40 | } else { |
||
| 41 | abort(400, "Module [{$name}] already exist!"); |
||
| 42 | } |
||
| 43 | |||
| 44 | return false; |
||
| 45 | } |
||
| 46 | } |
||
| 47 | |||
| 48 | // Get data from module.json. |
||
| 49 | $data = $this->getStubContents('json'); |
||
| 50 | $data = json_decode($data, true); |
||
| 51 | $data['path'] = $this->module->getModulePath($this->getName()); |
||
| 52 | if ($this->type === 'plain') { |
||
| 53 | $data['provider'] = []; |
||
| 54 | } |
||
| 55 | $this->module->getModel()->create($data); |
||
| 56 | |||
| 57 | $this->generateFolders(); |
||
| 58 | |||
| 59 | $this->generateModuleJsonFile(); |
||
| 60 | |||
| 61 | if ($this->type !== 'plain') { |
||
| 62 | $this->generateFiles(); |
||
| 63 | $this->generateResources(); |
||
| 64 | } |
||
| 65 | |||
| 66 | // Re-check if we created successfully. |
||
| 67 | $success = $this->module->has($name); |
||
| 68 | if ($success) { |
||
| 69 | if (!$this->silentOutput) { |
||
| 70 | $this->console->info("Module [{$name}] created successfully."); |
||
| 71 | } |
||
| 72 | } |
||
| 73 | |||
| 74 | return $success; |
||
| 75 | }); |
||
| 76 | } |
||
| 77 | |||
| 78 | /** |
||
| 79 | * Generate the files. |
||
| 80 | */ |
||
| 81 | View Code Duplication | public function generateFiles() |
|
| 97 | |||
| 98 | /** |
||
| 99 | * Generate some resources. |
||
| 100 | */ |
||
| 101 | public function generateResources() |
||
| 132 | |||
| 133 | /** |
||
| 134 | * Generate the module.json file |
||
| 135 | */ |
||
| 136 | View Code Duplication | private function generateModuleJsonFile() |
|
| 150 | } |
||
| 151 |
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.