Passed
Push — master ( 9bc01c...2c8da9 )
by Mohammad
03:42
created

Generator::makeViewsAndLanguage()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 20
nc 5
nop 1
dl 0
loc 29
rs 9.6
c 0
b 0
f 0
1
<?php
2
3
namespace Shamaseen\Repository\Generator\Commands;
4
5
use Config;
6
use Illuminate\Console\Command;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Facades\File;
9
use Illuminate\Support\Str;
10
use ReflectionClass;
11
use ReflectionException;
12
use Shamaseen\Repository\Generator\Forms\FormGenerator;
13
14
/**
15
 * Class RepositoryGenerator.
16
 */
17
class Generator extends Command
18
{
19
    /**
20
     * The name and signature of the console command.
21
     *
22
     * @var string
23
     */
24
    protected $signature = 'make:repository
25
    {name : Class (singular) for example User} {--only-view}';
26
27
    /**
28
     * The console command description.
29
     *
30
     * @var string
31
     */
32
    protected $description = 'Create repository generator';
33
34
    /**
35
     * The repository name.
36
     *
37
     * @var string
38
     */
39
    protected $repoName;
40
    /**
41
     * The repository name space.
42
     *
43
     * @var string
44
     */
45
    protected $repoNamespace;
46
    private $FormGenerator;
47
48
    /**
49
     * Create a new command instance.
50
     */
51
    public function __construct()
52
    {
53
        parent::__construct();
54
        $this->FormGenerator = new FormGenerator();
55
    }
56
57
    /**
58
     * Execute the console command.
59
     *
60
     * @throws ReflectionException
61
     */
62
    public function handle()
63
    {
64
        $file = preg_split(' (/|\\\\) ', (string) $this->argument('name')) ?? [];
65
66
        if (! $file) {
67
            return 'Something wrong with the inputs !';
68
        }
69
70
        $this->repoName = $file[count($file) - 1];
71
72
        unset($file[count($file) - 1]);
73
        $path = implode('\\', $file);
74
75
        if ($this->option('only-view')) {
76
            $this->makeViewsAndLanguage($path);
77
            $this->dumpAutoload();
78
            return true;
79
        }
80
81
        return $this->makeRepositoryPatternFiles($path);
82
    }
83
84
    public function makeRepositoryPatternFiles($path)
85
    {
86
        $model = Str::plural(Config::get('repository.model'));
87
        $interface = Str::plural(Config::get('repository.interface'));
88
        $repository = Str::plural(Config::get('repository.repository'));
89
90
        $this->generate($path, Config::get('repository.controllers_folder'), 'Controller');
91
        $this->generate($path, $model, 'Entity');
92
        $this->generate($path, Config::get('repository.requests_folder'), 'Request');
93
        $this->generate($path, $interface, 'Interface');
94
        $this->generate($path, $repository, 'Repository');
95
96
        $webFile = Config::get('repository.route_path').'/web.php';
97
        $pluralName = strtolower(Str::plural($this->repoName));
98
        $controllerPath = $path.'\\'.$this->repoName.'Controller';
99
100
        $webContent = "\nRoute::resource('{$pluralName}', '{$controllerPath}');";
101
102
        File::append($webFile, $webContent);
103
104
        $this->dumpAutoload();
105
        return true;
106
    }
107
108
    /**
109
     * @param $path
110
     *
111
     * @throws ReflectionException
112
     */
113
    public function makeViewsAndLanguage($path)
114
    {
115
        $entity = $this->getEntity($path);
116
117
        $createHtml = '';
118
        $editHtml = '';
119
        if ($entity instanceof Model) {
120
            $createHtml = $this->FormGenerator->generateForm($entity);
121
            $editHtml = $this->FormGenerator->generateForm($entity, 'put');
122
        } else {
123
            $message = "There is no entity for {$this->repoName}, 
124
                        do you want to continue (this will disable form generator) ?";
125
            if (! $this->confirm($message)) {
126
                echo 'Dispatch ..';
127
                die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
128
            }
129
        }
130
        $repositoryName = lcfirst($this->repoName);
131
        $viewsPath = Config::get('repository.resources_path').'/views';
132
        $languagePath = Config::get('repository.lang_path');
133
134
        foreach (Config::get('repository.languages') as $lang) {
135
            $this->generate($repositoryName, "{$languagePath}/{$lang}", 'lang');
136
        }
137
138
        $this->generate($repositoryName, $viewsPath, 'create', $createHtml);
139
        $this->generate($repositoryName, $viewsPath, 'edit', $editHtml);
140
        $this->generate($repositoryName, $viewsPath, 'index');
141
        $this->generate($repositoryName, $viewsPath, 'show');
142
    }
143
144
    /**
145
     * @param $path
146
     *
147
     * @throws ReflectionException
148
     *
149
     * @return bool|Model|object
150
     */
151
    public function getEntity($path)
152
    {
153
        $myClass = 'App\Entities\\'.$path.'\\'.$this->repoName;
154
        if (! class_exists($myClass)) {
155
            return false;
156
        }
157
158
        $reflect = new ReflectionClass($myClass);
159
160
        return $reflect->newInstance();
161
    }
162
163
    /**
164
     * Get stub content to generate needed files.
165
     *
166
     * @param string $type determine which stub should choose to get content
167
     *
168
     * @return false|string
169
     */
170
    protected function getStub($type)
171
    {
172
        return file_get_contents(Config::get('repository.stubs_path')."/$type.stub");
173
    }
174
175
    /**
176
     * @param string $path   Class path
177
     * @param string $folder default path to generate in
178
     * @param string $type   define which kind of files should generate
179
     * @param string $form
180
     *
181
     * @return bool
182
     */
183
    protected function generate($path, $folder, $type, $form = '')
184
    {
185
        $path = $path ? '\\'.$path : '';
186
        $content = $this->getStub($type);
187
188
        if (false === $content) {
189
            echo 'file '.$type.'.stub is not exist !';
190
191
            return false;
192
        }
193
194
        $template = str_replace(
195
            [
196
                '{{modelName}}',
197
                '{{lcPluralModelName}}',
198
                '{{folder}}',
199
                '{{path}}',
200
                '{{modelBaseFolderName}}',
201
                '{{interfaceBaseFolderName}}',
202
                '{{form}}',
203
            ],
204
            [
205
                $this->repoName,
206
                Str::plural(lcfirst($this->repoName)),
207
                Str::plural($folder),
208
                $path,
209
                Str::plural(Config::get('repository.model', 'Entity')),
210
                Str::plural(Config::get('repository.interface', 'Interface')),
211
                $form,
212
            ],
213
            $this->getStub($type)
214
        );
215
216
        $folder = str_replace('\\', '/', $folder);
217
        $path = str_replace('\\', '/', $path);
218
        $this->type($type, $folder, $path, $template);
219
220
        return true;
221
    }
222
223
    /**
224
     * Check if folder exist.
225
     *
226
     * @param string $path class path
227
     *
228
     * @return string
229
     */
230
    public function getFolderOrCreate($path)
231
    {
232
        if (! file_exists($path)) {
233
            mkdir($path, 0777, true);
234
        }
235
236
        return $path;
237
    }
238
239
    /**
240
     * @param string $path     Class path
241
     * @param string $folder   default path to generate in
242
     * @param string $type     define which kind of files should generate
243
     * @param string $template temple file
244
     *
245
     * return void
246
     */
247
    private function type($type, $folder, $path, $template)
248
    {
249
        switch ($type) {
250
            case 'Entity':
251
                $filePath = $this->getFolderOrCreate(Config::get('repository.app_path')."/{$folder}/{$path}");
252
                $filePath = rtrim($filePath, '/');
253
                $content = "{$filePath}/{$this->repoName}.php";
254
255
                break;
256
            case 'Controller':
257
            case 'Request':
258
            case 'Repository':
259
            case 'Interface':
260
                $filePath = $this->getFolderOrCreate(Config::get('repository.app_path')."/{$folder}/{$path}");
261
                $filePath = rtrim($filePath, '/');
262
                $content = "{$filePath}/{$this->repoName}{$type}.php";
263
                break;
264
            case 'create':
265
            case 'edit':
266
            case 'index':
267
            case 'show':
268
                $filePath = $this->getFolderOrCreate($folder.'/'.Str::plural($path)).'/';
269
                $repoName = lcfirst($type);
270
                $content = $filePath.$repoName.'.blade.php';
271
                break;
272
            default:
273
                $filePath = $this->getFolderOrCreate($folder).'/';
274
                $repoName = lcfirst($this->repoName);
275
                $content = $filePath.$repoName.'.php';
276
        }
277
        file_put_contents($content, $template);
278
    }
279
280
    function dumpAutoload()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
281
    {
282
        shell_exec('composer dump-autoload');
283
    }
284
}
285