Completed
Pull Request — master (#1163)
by
unknown
01:51
created

DatabaseModuleGenerator::generateResources()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 12
nop 0
dl 0
loc 31
rs 9.1128
c 0
b 0
f 0
1
<?php
2
3
namespace Nwidart\Modules\Generators;
4
5
use Illuminate\Filesystem\Filesystem;
6
use Illuminate\Support\Facades\Artisan;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Facades\File;
9
use Nwidart\Modules\Laravel\LaravelDatabaseRepository;
10
use Nwidart\Modules\Support\Config\GenerateConfigReader;
11
12
/**
13
 * Class DatabaseModuleGenerator.
14
 * @package Nwidart\Modules\Generators
15
 * @property LaravelDatabaseRepository $module
16
 */
17
class DatabaseModuleGenerator extends ModuleGenerator
18
{
19
    protected $silentOutput = false;
20
21
    public function setSilentOutput($bool = true)
22
    {
23
        $this->silentOutput = $bool;
24
25
        return $this;
26
    }
27
28
    /**
29
     * Generate the module.
30
     */
31
    public function generate(): int
32
    {
33
        return DB::transaction(function () {
34
            $name = $this->getName();
35
36 View Code Duplication
            if ($this->module->has($name)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
37
                if ($this->force) {
38
                    $this->module->delete($name);
39
                } else {
40
                    if (!$this->silentOutput) {
41
                        $this->console->info("Module [{$name}] already exist!");
42
                    } else {
43
                        abort(400, "Module [{$name}] already exist!");
44
                    }
45
46
                    return false;
47
                }
48
            }
49
50
            // Get data from module.json.
51
            $data = $this->getStubContents('json');
52
            $data = json_decode($data, true);
53
            $data['path'] = $this->module->getModulePath($this->getName());
54
            if ($this->type === 'plain') {
55
                $data['provider'] = [];
56
            }
57
            $this->module->getModel()->create($data);
58
59
            // Check when folder exists, just remove it.
60
            if (File::isDirectory($data['path'])) {
0 ignored issues
show
Bug introduced by
It seems like $data['path'] can also be of type array; however, Illuminate\Support\Facades\File::isDirectory() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
61
                if ($this->force) {
62
                    (new Filesystem())->deleteDirectory($data['path']);
0 ignored issues
show
Bug introduced by
It seems like $data['path'] can also be of type array; however, Illuminate\Filesystem\Fi...stem::deleteDirectory() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
63
                } else {
64
                    abort(400, "Directory exists.");
65
                }
66
            }
67
68
            $this->generateFolders();
69
70
            $this->generateModuleJsonFile();
71
72
            if ($this->type !== 'plain') {
73
                $this->generateFiles();
74
                $this->generateResources();
75
            }
76
77
            // Re-check if we created successfully.
78
            $success = $this->module->has($name);
79
            if ($success) {
80
                if (!$this->silentOutput) {
81
                    $this->console->info("Module [{$name}] created successfully.");
82
                }
83
            }
84
85
            return $success;
86
        });
87
    }
88
89
    /**
90
     * Generate the files.
91
     */
92 View Code Duplication
    public function generateFiles()
93
    {
94
        foreach ($this->getFiles() as $stub => $file) {
95
            $path = $this->module->getModulePath($this->getName()) . $file;
96
97
            if (!$this->filesystem->isDirectory($dir = dirname($path))) {
98
                $this->filesystem->makeDirectory($dir, 0775, true);
99
            }
100
101
            $this->filesystem->put($path, $this->getStubContents($stub));
102
103
            if (!$this->silentOutput) {
104
                $this->console->info("Created : {$path}");
105
            }
106
        }
107
    }
108
109
    /**
110
     * Generate some resources.
111
     */
112
    public function generateResources()
113
    {
114
        $moduleName = $this->getName();
115
116
        if (GenerateConfigReader::read('seeder')->generate() === true) {
117
            Artisan::call('module:make-seed', [
118
                'name'     => $moduleName,
119
                'module'   => $moduleName,
120
                '--master' => true,
121
            ]);
122
        }
123
124
        if (GenerateConfigReader::read('provider')->generate() === true) {
125
            Artisan::call('module:make-provider', [
126
                'name'     => $moduleName . 'ServiceProvider',
127
                'module'   => $moduleName,
128
                '--master' => true,
129
            ]);
130
            Artisan::call('module:route-provider', [
131
                'module' => $moduleName,
132
            ]);
133
        }
134
135
        if (GenerateConfigReader::read('controller')->generate() === true) {
136
            $options = $this->type == 'api' ? ['--api' => true] : [];
137
            Artisan::call('module:make-controller', [
138
                    'controller' => $moduleName . 'Controller',
139
                    'module'     => $moduleName,
140
                ] + $options);
141
        }
142
    }
143
144
    /**
145
     * Generate the module.json file
146
     */
147 View Code Duplication
    private function generateModuleJsonFile()
0 ignored issues
show
Bug introduced by
Consider using a different method name as you override a private method of the parent class.

Overwriting private methods is generally fine as long as you also use private visibility. It might still be preferable for understandability to use a different method name.

Loading history...
148
    {
149
        $path = $this->module->getModulePath($this->getName()) . 'module.json';
150
151
        if (!$this->filesystem->isDirectory($dir = dirname($path))) {
152
            $this->filesystem->makeDirectory($dir, 0775, true);
153
        }
154
155
        $this->filesystem->put($path, $this->getStubContents('json'));
156
157
        if (!$this->silentOutput) {
158
            $this->console->info("Created : {$path}");
159
        }
160
    }
161
}
162