Passed
Pull Request — 2.x (#729)
by Antonio Carlos
06:06
created

ModuleMake::checkCapsuleDirectory()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 37.8525

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 7
nop 1
dl 0
loc 21
ccs 2
cts 14
cp 0.1429
crap 37.8525
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace A17\Twill\Commands;
4
5
use Illuminate\Support\Facades\File;
6
use Illuminate\Config\Repository as Config;
7
use Illuminate\Filesystem\Filesystem;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Composer;
10
use Illuminate\Support\Str;
11
12
class ModuleMake extends Command
13
{
14
    /**
15
     * The name and signature of the console command.
16
     *
17
     * @var string
18
     */
19
    protected $signature = 'twill:make:module {moduleName}
20
        {--B|hasBlocks}
21
        {--T|hasTranslation}
22
        {--S|hasSlug}
23
        {--M|hasMedias}
24
        {--F|hasFiles}
25
        {--P|hasPosition}
26
        {--R|hasRevisions}
27
        {--all}';
28
29
    /**
30
     * The console command description.
31
     *
32
     * @var string
33
     */
34
    protected $description = 'Create a new Twill Module';
35
36
    /**
37
     * @var Filesystem
38
     */
39
    protected $files;
40
41
    /**
42
     * @var Composer
43
     */
44
    protected $composer;
45
46
    /**
47
     * @var string[]
48
     */
49
    protected $modelTraits;
50
51
    /**
52
     * @var string[]
53
     */
54
    protected $repositoryTraits;
55
56
    /**
57
     * @var Config
58
     */
59
    protected $config;
60
61
    /**
62
     * @var bool
63
     */
64
    protected $blockable;
65
66
    /**
67
     * @var bool
68
     */
69
    protected $translatable;
70
71
    /**
72
     * @var bool
73
     */
74
    protected $sluggable;
75
76
    /**
77
     * @var bool
78
     */
79
    protected $mediable;
80
81
    /**
82
     * @var bool
83
     */
84
    protected $fileable;
85
86
    /**
87
     * @var bool
88
     */
89
    protected $sortable;
90
91
    /**
92
     * @var bool
93
     */
94
    protected $revisionable;
95
96
    /**
97
     * @var bool
98
     */
99
    protected $defaultsAnswserToNo;
100
101
    /**
102
     * @var bool
103
     */
104
    protected $isCapsule = false;
105
106
    /**
107
     * @var string
108
     */
109
    protected $moduleBasePath;
110
111
    /**
112
     * @var string
113
     */
114
    protected $capsule;
115
116
    /**
117
     * @param Filesystem $files
118
     * @param Composer $composer
119
     * @param Config $config
120
     */
121 76
    public function __construct(Filesystem $files, Composer $composer, Config $config)
122
    {
123 76
        parent::__construct();
124
125 76
        $this->files = $files;
126 76
        $this->composer = $composer;
127 76
        $this->config = $config;
128
129 76
        $this->blockable = false;
130 76
        $this->translatable = false;
131 76
        $this->sluggable = false;
132 76
        $this->mediable = false;
133 76
        $this->fileable = false;
134 76
        $this->sortable = false;
135 76
        $this->revisionable = false;
136
137 76
        $this->defaultsAnswserToNo = false;
138
139 76
        $this->modelTraits = ['HasBlocks', 'HasTranslation', 'HasSlug', 'HasMedias', 'HasFiles', 'HasRevisions', 'HasPosition'];
140 76
        $this->repositoryTraits = ['HandleBlocks', 'HandleTranslations', 'HandleSlugs', 'HandleMedias', 'HandleFiles', 'HandleRevisions'];
141 76
    }
142
143 7
    protected function checkCapsuleDirectory($dir)
144
    {
145 7
        if (file_exists($dir)) {
146
            if (!$this->option('force')) {
147
                $answer = $this->choice("Capsule path exists ({$dir}). Erase and overwrite?",
148
                    ['no', 'yes'], $this->defaultsAnswserToNo
149
                        ? 0
150
                        : 1);
151
            }
152
153
            if ('yes' === ($answer ?? 'no') || $this->option('force')) {
154
                File::deleteDirectory($dir);
155
156
                if (file_exists($dir)) {
157
                    $this->info("Directory could not be deleted. Aborted.");
158
                    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...
159
                }
160
            } else {
161
                $this->info("Aborted");
162
163
                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...
164
            }
165
        }
166 7
    }
167
168
    /**
169
     * Executes the console command.
170
     *
171
     * @return mixed
172
     */
173 8
    public function handle()
174
    {
175 8
        $moduleName = Str::camel(Str::plural(lcfirst($this->argument('moduleName'))));
0 ignored issues
show
Bug introduced by
It seems like $this->argument('moduleName') can also be of type string[]; however, parameter $str of lcfirst() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

175
        $moduleName = Str::camel(Str::plural(lcfirst(/** @scrutinizer ignore-type */ $this->argument('moduleName'))));
Loading history...
176
177 8
        $this->capsule = app('twill.capsules.manager')->makeCapsule(['name' => $moduleName], config("twill.capsules.path"));
0 ignored issues
show
Bug introduced by
The method makeCapsule() 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

177
        $this->capsule = app('twill.capsules.manager')->/** @scrutinizer ignore-call */ makeCapsule(['name' => $moduleName], config("twill.capsules.path"));

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...
178
179 8
        $enabledOptions = Collection::make($this->options())->only([
180 8
            'hasBlocks',
181
            'hasTranslation',
182
            'hasSlug',
183
            'hasMedias',
184
            'hasFiles',
185
            'hasPosition',
186
            'hasRevisions',
187 8
        ])->filter(function ($enabled) {
188 8
            return $enabled;
189 8
        });
190
191 8
        if (count($enabledOptions) > 0) {
192 1
            $this->defaultsAnswserToNo = true;
193
        }
194
195 8
        $this->blockable = $this->checkOption('hasBlocks');
196 8
        $this->translatable = $this->checkOption('hasTranslation');
197 8
        $this->sluggable = $this->checkOption('hasSlug');
198 8
        $this->mediable = $this->checkOption('hasMedias');
199 8
        $this->fileable = $this->checkOption('hasFiles');
200 8
        $this->sortable = $this->checkOption('hasPosition');
201 8
        $this->revisionable = $this->checkOption('hasRevisions');
202
203
        $activeTraits = [
204 8
            $this->blockable,
205 8
            $this->translatable,
206 8
            $this->sluggable,
207 8
            $this->mediable,
208 8
            $this->fileable,
209 8
            $this->revisionable,
210 8
            $this->sortable,
211
        ];
212
213 8
        $modelName = Str::studly(Str::singular($moduleName));
214
215 8
        $this->createCapsuleNamespace(Str::studly($moduleName), $modelName);
216
217 8
        $this->createCapsulePath(Str::studly($moduleName), $modelName);
218
219 8
        $this->createMigration($moduleName);
220 8
        $this->createModels($modelName, $activeTraits);
221 8
        $this->createRepository($modelName, $activeTraits);
222 8
        $this->createController($moduleName, $modelName);
223 8
        $this->createRequest($modelName);
224 8
        $this->createViews($moduleName);
225 8
        $this->createRoutes($moduleName);
0 ignored issues
show
Unused Code introduced by
The call to A17\Twill\Commands\ModuleMake::createRoutes() has too many arguments starting with $moduleName. ( Ignorable by Annotation )

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

225
        $this->/** @scrutinizer ignore-call */ 
226
               createRoutes($moduleName);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
226 8
        $this->createSeed($moduleName);
227
228 8
        $this->info("Add Route::module('{$moduleName}'); to your admin routes file.");
229 8
        $this->info("Setup a new CMS menu item in config/twill-navigation.php:");
230
231 8
        $navTitle = Str::studly($moduleName);
232
233 8
        $this->info("
234 8
            '{$moduleName}' => [
235 8
                'title' => '{$navTitle}',
236
                'module' => true
237
            ]
238
        ");
239
240 8
        if ($this->isCapsule) {
241 7
            $this->info("Setup your new Capsule on config/twill.php:");
242
243 7
            $navTitle = Str::studly($moduleName);
0 ignored issues
show
Unused Code introduced by
The assignment to $navTitle is dead and can be removed.
Loading history...
244
245 7
            $this->info("
246
                'capsules' => [
247 7
                    'name' => '{$this->capsule['name']}',
248
                    'enabled' => true
249
                ]
250
            ");
251
        }
252
253 8
        $this->info("Migrate your database.\n");
254
255 8
        $this->info("Enjoy.");
256
257 8
        $this->composer->dumpAutoloads();
258 8
    }
259
260
    /**
261
     * Creates a new module database migration file.
262
     *
263
     * @param string $moduleName
264
     * @return void
265
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
266
     */
267 8
    private function createMigration($moduleName = 'items')
268
    {
269 8
        $table = Str::snake($moduleName);
270 8
        $tableClassName = Str::studly($table);
271
272 8
        $className = "Create{$tableClassName}Tables";
0 ignored issues
show
Unused Code introduced by
The assignment to $className is dead and can be removed.
Loading history...
273
274 8
        $migrationName = 'create_' . $table . '_tables';
275
276 8
        if (!count(glob($this->databasePath('migrations/*' . $migrationName . '.php')))) {
0 ignored issues
show
Bug introduced by
It seems like glob($this->databasePath...igrationName . '.php')) can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

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

276
        if (!count(/** @scrutinizer ignore-type */ glob($this->databasePath('migrations/*' . $migrationName . '.php')))) {
Loading history...
277 8
            $migrationPath = $this->databasePath() . '/migrations';
278
279 8
            $this->makeDir($migrationPath);
280
281 8
            $fullPath = $this->laravel['migration.creator']->create($migrationName, $migrationPath);
282
283 8
            $stub = str_replace(
284 8
                ['{{table}}', '{{singularTableName}}', '{{tableClassName}}'],
285 8
                [$table, Str::singular($table), $tableClassName],
286 8
                $this->files->get(__DIR__ . '/stubs/migration.stub')
287
            );
288
289 8
            if ($this->translatable) {
290 8
                $stub = preg_replace('/{{!hasTranslation}}[\s\S]+?{{\/!hasTranslation}}/', '', $stub);
291
            } else {
292
                $stub = str_replace([
293
                    '{{!hasTranslation}}',
294
                    '{{/!hasTranslation}}',
295
                ], '', $stub);
296
            }
297
298 8
            $stub = $this->renderStubForOption($stub, 'hasTranslation', $this->translatable);
299 8
            $stub = $this->renderStubForOption($stub, 'hasSlug', $this->sluggable);
300 8
            $stub = $this->renderStubForOption($stub, 'hasRevisions', $this->revisionable);
301 8
            $stub = $this->renderStubForOption($stub, 'hasPosition', $this->sortable);
302
303 8
            $stub = preg_replace('/\}\);[\s\S]+?Schema::create/', "});\n\n        Schema::create", $stub);
304
305 8
            $this->files->put($fullPath, $stub);
306
307 8
            $this->info("Migration created successfully! Add some fields!");
308
        }
309 8
    }
310
311
    /**
312
     * Creates new model class files for the given model name and traits.
313
     *
314
     * @param string $modelName
315
     * @param array $activeTraits
316
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
317
     */
318 8
    private function createModels($modelName = 'Item', $activeTraits = [])
319
    {
320 8
        $modelClassName = $this->namespace('models', 'Models', $modelName);
321
322 8
        $modelsDir = $this->isCapsule ? $this->capsule['models_dir'] : 'Models';
323
324 8
        $this->makeTwillDirectory($modelsDir);
325
326 8
        if ($this->translatable) {
327 8
            $this->makeTwillDirectory($baseDir = $this->isCapsule ? $modelsDir : "{$modelsDir}/Translations");
328
329 8
            $modelTranslationClassName = $modelName . 'Translation';
330
331 8
            $stub = str_replace(
332 8
                ['{{modelTranslationClassName}}', '{{modelClassWithNamespace}}', '{{modelClassName}}', '{{namespace}}'],
333 8
                [$modelTranslationClassName, $modelClassName, $modelName, $this->namespace('models', 'Models\Translations')],
334 8
                $this->files->get(__DIR__ . '/stubs/model_translation.stub')
335
            );
336
337 8
            twill_put_stub(twill_path("{$baseDir}/" . $modelTranslationClassName . '.php'), $stub);
338
        }
339
340 8
        if ($this->sluggable) {
341 8
            $this->makeTwillDirectory($baseDir = $this->isCapsule ? $modelsDir : "{$modelsDir}/Slugs");
342
343 8
            $modelSlugClassName = $modelName . 'Slug';
344
345 8
            $stub = str_replace(
346 8
                ['{{modelSlugClassName}}', '{{modelClassWithNamespace}}', '{{modelName}}', '{{namespace}}'],
347 8
                [$modelSlugClassName, $modelClassName, Str::snake($modelName), $this->namespace('models', 'Models\Slugs')],
348 8
                $this->files->get(__DIR__ . '/stubs/model_slug.stub')
349
            );
350
351 8
            twill_put_stub(twill_path("{$baseDir}/" . $modelSlugClassName . '.php'), $stub);
352
        }
353
354 8
        if ($this->revisionable) {
355 8
            $this->makeTwillDirectory($baseDir = $this->isCapsule ? $modelsDir : "{$modelsDir}/Revisions");
356
357 8
            $modelRevisionClassName = $modelName . 'Revision';
358
359 8
            $stub = str_replace(
360 8
                ['{{modelRevisionClassName}}', '{{modelClassWithNamespace}}', '{{modelName}}', '{{namespace}}'],
361 8
                [$modelRevisionClassName, $modelClassName, Str::snake($modelName), $this->namespace('models', 'Models\Revisions')],
362 8
                $this->files->get(__DIR__ . '/stubs/model_revision.stub')
363
            );
364
365 8
            twill_put_stub(twill_path("{$baseDir}/" . $modelRevisionClassName . '.php'), $stub);
366
        }
367
368 8
        $activeModelTraits = [];
369
370 8
        foreach ($activeTraits as $index => $traitIsActive) {
371 8
            if ($traitIsActive) {
372 8
                !isset($this->modelTraits[$index]) ?: $activeModelTraits[] = $this->modelTraits[$index];
373
            }
374
        }
375
376 8
        $activeModelTraitsString = empty($activeModelTraits) ? '' : 'use ' . rtrim(implode(', ', $activeModelTraits), ', ') . ';';
377
378 8
        $activeModelTraitsImports = empty($activeModelTraits) ? '' : "use A17\Twill\Models\Behaviors\\" . implode(";\nuse A17\Twill\Models\Behaviors\\", $activeModelTraits) . ";";
379
380 8
        $activeModelImplements = $this->sortable ? 'implements Sortable' : '';
381
382 8
        if ($this->sortable) {
383 8
            $activeModelTraitsImports .= "\nuse A17\Twill\Models\Behaviors\Sortable;";
384
        }
385
386 8
        $stub = str_replace([
387 8
            '{{modelClassName}}',
388
            '{{modelTraits}}',
389
            '{{modelImports}}',
390
            '{{modelImplements}}',
391
            '{{namespace}}',
392
        ], [
393 8
            $modelName,
394 8
            $activeModelTraitsString,
395 8
            $activeModelTraitsImports,
396 8
            $activeModelImplements,
397 8
            $this->namespace('models', 'Models')
398 8
        ], $this->files->get(__DIR__ . '/stubs/model.stub'));
399
400 8
        $stub = $this->renderStubForOption($stub, 'hasTranslation', $this->translatable);
401 8
        $stub = $this->renderStubForOption($stub, 'hasSlug', $this->sluggable);
402 8
        $stub = $this->renderStubForOption($stub, 'hasMedias', $this->mediable);
403 8
        $stub = $this->renderStubForOption($stub, 'hasPosition', $this->sortable);
404
405 8
        twill_put_stub(twill_path("{$modelsDir}/" . $modelName . '.php'), $stub);
406
407 8
        $this->info("Models created successfully! Fill your fillables!");
408 8
    }
409
410 8
    private function renderStubForOption($stub, $option, $enabled)
411
    {
412 8
        if ($enabled) {
413 8
            $stub = str_replace([
414 8
                '{{' . $option . '}}',
415 8
                '{{/' . $option . '}}',
416 8
            ], '', $stub);
417
        } else {
418
            $stub = preg_replace('/{{' . $option . '}}[\s\S]+?{{\/' . $option . '}}/', '', $stub);
419
        }
420
421 8
        return $stub;
422
    }
423
424
    /**
425
     * Creates new repository class file for the given model name.
426
     *
427
     * @param string $modelName
428
     * @param array $activeTraits
429
     * @return void
430
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
431
     */
432 8
    private function createRepository($modelName = 'Item', $activeTraits = [])
433
    {
434 8
        $modelsDir = $this->isCapsule ? $this->capsule['repositories_dir'] : 'Repositories';
435
436 8
        $modelClass = $this->isCapsule ? $this->capsule['model'] : "App\Models\\{$this->capsule['singular']}";
437
438 8
        $this->makeTwillDirectory($modelsDir);
439
440 8
        $repositoryClassName = $modelName . 'Repository';
441
442 8
        $activeRepositoryTraits = [];
443
444 8
        foreach ($activeTraits as $index => $traitIsActive) {
445 8
            if ($traitIsActive) {
446 8
                !isset($this->repositoryTraits[$index]) ?: $activeRepositoryTraits[] = $this->repositoryTraits[$index];
447
            }
448
        }
449
450 8
        $activeRepositoryTraitsString = empty($activeRepositoryTraits) ? '' : 'use ' . (empty($activeRepositoryTraits) ? "" : rtrim(implode(', ', $activeRepositoryTraits), ', ') . ';');
451
452 8
        $activeRepositoryTraitsImports = empty($activeRepositoryTraits) ? '' : "use A17\Twill\Repositories\Behaviors\\" . implode(";\nuse A17\Twill\Repositories\Behaviors\\", $activeRepositoryTraits) . ";";
453
454 8
        $stub = str_replace(
455 8
            ['{{repositoryClassName}}', '{{modelName}}', '{{repositoryTraits}}', '{{repositoryImports}}', '{{namespace}}', '{{modelClass}}'],
456 8
            [$repositoryClassName, $modelName, $activeRepositoryTraitsString, $activeRepositoryTraitsImports,$this->namespace('repositories', 'Repositories'), $modelClass],
457 8
            $this->files->get(__DIR__ . '/stubs/repository.stub')
458
        );
459
460 8
        twill_put_stub(twill_path("{$modelsDir}/" . $repositoryClassName . '.php'), $stub);
461
462 8
        $this->info("Repository created successfully! Control all the things!");
463 8
    }
464
465
    /**
466
     * Create a new controller class file for the given module name and model name.
467
     *
468
     * @param string $moduleName
469
     * @param string $modelName
470
     * @return void
471
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
472
     */
473 8
    private function createController($moduleName = 'items', $modelName = 'Item')
474
    {
475 8
        $controllerClassName = $modelName . 'Controller';
476
477 8
        $dir = $this->isCapsule ? $this->capsule['controllers_dir'] : 'Http/Controllers/Admin';
478
479 8
        $this->makeTwillDirectory($dir);
480
481 8
        $stub = str_replace(
482 8
            ['{{moduleName}}', '{{controllerClassName}}', '{{namespace}}'],
483 8
            [$moduleName, $controllerClassName,$this->namespace('controllers', 'Http\Controllers\Admin')],
484 8
            $this->files->get(__DIR__ . '/stubs/controller.stub')
485
        );
486
487 8
        twill_put_stub(twill_path("{$dir}/" . $controllerClassName . '.php'), $stub);
488
489 8
        $this->info("Controller created successfully! Define your index/browser/form endpoints options!");
490 8
    }
491
492
    /**
493
     * Creates a new request class file for the given model name.
494
     *
495
     * @param string $modelName
496
     * @return void
497
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
498
     */
499 8
    private function createRequest($modelName = 'Item')
500
    {
501 8
        $dir = $this->isCapsule ? $this->capsule['requests_dir'] : 'Http/Requests/Admin';
502
503 8
        $this->makeTwillDirectory($dir);
504
505 8
        $requestClassName = $modelName . 'Request';
506
507 8
        $stub = str_replace(
508 8
            ['{{requestClassName}}','{{namespace}}'],
509 8
            [$requestClassName,$this->namespace('requests', 'Http\Requests\Admin')],
510 8
            $this->files->get(__DIR__ . '/stubs/request.stub')
511
        );
512
513 8
        twill_put_stub(twill_path("{$dir}/" . $requestClassName . '.php'), $stub);
514
515 8
        $this->info("Form request created successfully! Add some validation rules!");
516 8
    }
517
518
    /**
519
     * Creates appropriate module Blade view files.
520
     *
521
     * @param string $moduleName
522
     * @return void
523
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
524
     */
525 8
    private function createViews($moduleName = 'items')
526
    {
527 8
        $viewsPath = $this->viewPath($moduleName);
528
529 8
        $this->makeTwillDirectory($viewsPath);
530
531 8
        $formView = $this->translatable ? 'form_translatable' : 'form';
532
533 8
        twill_put_stub($viewsPath . '/form.blade.php', $this->files->get(__DIR__ . '/stubs/' . $formView . '.blade.stub'));
534
535 8
        $this->info("Form view created successfully! Include your form fields using @formField directives!");
536 8
    }
537
538
    /**
539
     * Creates a basic routes file for the Capsule.
540
     *
541
     * @param string $moduleName
542
     * @return void
543
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
544
     */
545 8
    public function createRoutes()
546
    {
547 8
        $this->makeDir($this->capsule['routes_file']);
548
549 8
        $contents = str_replace(
550 8
            '{{moduleName}}',
551 8
            $this->capsule['module'],
552 8
            $this->files->get(__DIR__ . '/stubs/routes_admin.stub')
553
        );
554
555 8
        twill_put_stub($this->capsule['routes_file'], $contents);
556
557 8
        $this->info("Routes file created successfully!");
558 8
    }
559
560
    /**
561
     * Creates a new module database seed file.
562
     *
563
     * @param string $moduleName
564
     * @return void
565
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
566
     */
567 8
    private function createSeed($moduleName = 'items')
568
    {
569 8
        $this->makeTwillDirectory($this->capsule['seeds_psr4_path']);
570
571 8
        $stub = $this->files->get(__DIR__ . '/stubs/database_seeder.stub');
572
573 8
        $stub = str_replace('{moduleName}', $this->capsule['plural'], $stub);
574
575 8
        $this->files->put("{$this->capsule['seeds_psr4_path']}/DatabaseSeeder.php", $stub);
576
577 8
        $this->info("Seed created successfully!");
578 8
    }
579
580 8
    private function checkOption($option)
581
    {
582 8
        if ($this->option($option) || $this->option('all')) {
583 8
            return true;
584
        }
585
586
        $questions = [
587
            'hasBlocks' => 'Do you need to use the block editor on this module?',
588
            'hasTranslation' => 'Do you need to translate content on this module?',
589
            'hasSlug' => 'Do you need to generate slugs on this module?',
590
            'hasMedias' => 'Do you need to attach images on this module?',
591
            'hasFiles' => 'Do you need to attach files on this module?',
592
            'hasPosition' => 'Do you need to manage the position of records on this module?',
593
            'hasRevisions' => 'Do you need to enable revisions on this module?',
594
        ];
595
596
        return 'yes' === $this->choice($questions[$option], ['no', 'yes'], $this->defaultsAnswserToNo ? 0 : 1);
597
    }
598
599 8
    public function createCapsulePath($moduleName, $modelName)
600
    {
601 8
        if (!$this->isCapsule) {
602 1
            $this->moduleBasePath = base_path();
603
604 1
            return;
605
        }
606
607 7
        $this->checkCapsuleDirectory(
608 7
            $this->moduleBasePath = config('twill.capsules.path')."/{$moduleName}"
609
        );
610
611 7
        $this->makeDir($this->moduleBasePath);
612 7
    }
613
614 8
    public function createCapsuleNamespace($module, $model)
615
    {
616 8
        $base = config('twill.capsules.namespace');
617
618 8
        $this->capsuleNamespace = "{$base}\\{$module}";
0 ignored issues
show
Bug Best Practice introduced by
The property capsuleNamespace does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
619 8
    }
620
621 8
    public function databasePath($path = '')
622
    {
623 8
        if (!$this->isCapsule) {
624 1
            return database_path($path);
625
        }
626
627 7
        return "{$this->moduleBasePath}/database" . (filled($path) ? "/{$path}" : '');
628
    }
629
630 8
    public function makeDir($dir)
631
    {
632 8
        $info = pathinfo($dir);
633
634 8
        $dir = isset($info['extension']) ? $info['dirname'] : $dir;
635
636 8
        if (!is_dir($dir))
637
        {
638 8
            mkdir($dir, 0755, true);
639
        }
640
641 8
        if (!is_dir($dir)) {
642
            $this->info("It wasn't possible to create capsule directory {$dir}");
643
644
            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...
645
        }
646 8
    }
647
648 8
    public function makeTwillDirectory($path)
649
    {
650 8
        make_twill_directory($path);
651 8
    }
652
653 8
    public function namespace($type, $suffix, $class = null)
654
    {
655 8
        $class = (filled($class) ? "\\$class" : '');
656
657 8
        if (!$this->isCapsule) {
658 1
            return "App\\{$suffix}{$class}";
659
        }
660
661 7
        return $this->capsule[$type] . $class;
662
    }
663
664 8
    public function viewPath($moduleName)
665
    {
666 8
        if (!$this->isCapsule) {
667 1
            return $viewsPath = $this->config->get('view.paths')[0] . '/admin/' . $moduleName;
0 ignored issues
show
Unused Code introduced by
The assignment to $viewsPath is dead and can be removed.
Loading history...
668
        }
669
670 7
        $this->makeDir($dir = "{$this->moduleBasePath}/resources/views/admin");
671
672 7
        return $dir;
673
    }
674
}
675