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

ModuleMake::checkOption()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
nc 2
nop 1
dl 0
loc 17
ccs 0
cts 0
cp 0
crap 20
rs 9.9
c 1
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 69
106
    /**
107 69
     * @var string
108
     */
109 69
    protected $moduleBasePath;
110 69
111 69
    /**
112
     * @var string
113 69
     */
114 69
    protected $capsule;
115 69
116 69
    /**
117 69
     * @param Filesystem $files
118 69
     * @param Composer $composer
119 69
     * @param Config $config
120
     */
121 69
    public function __construct(Filesystem $files, Composer $composer, Config $config)
122
    {
123 69
        parent::__construct();
124 69
125 69
        $this->files = $files;
126
        $this->composer = $composer;
127
        $this->config = $config;
128
129
        $this->blockable = false;
130
        $this->translatable = false;
131
        $this->sluggable = false;
132 1
        $this->mediable = false;
133
        $this->fileable = false;
134 1
        $this->sortable = false;
135
        $this->revisionable = false;
136 1
137 1
        $this->defaultsAnswserToNo = false;
138
139
        $this->modelTraits = ['HasBlocks', 'HasTranslation', 'HasSlug', 'HasMedias', 'HasFiles', 'HasRevisions', 'HasPosition'];
140
        $this->repositoryTraits = ['HandleBlocks', 'HandleTranslations', 'HandleSlugs', 'HandleMedias', 'HandleFiles', 'HandleRevisions'];
141
    }
142
143
    protected function checkCapsuleDirectory($dir)
144
    {
145 1
        if (file_exists($dir)) {
146 1
            if (!$this->option('force')) {
147
                $answer = $this->choice("Capsule path exists ({$dir}). Erase and overwrite?",
148 1
                    ['no', 'yes'], $this->defaultsAnswserToNo
149 1
                        ? 0
150
                        : 1);
151
            }
152 1
153 1
            if ('yes' === ($answer ?? 'no') || $this->option('force')) {
154 1
                File::deleteDirectory($dir);
155 1
156 1
                if (file_exists($dir)) {
157 1
                    $this->info("Directory could not be deleted. Aborted.");
158 1
                    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 1
                $this->info("Aborted");
162 1
163 1
                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 1
            }
165 1
        }
166 1
    }
167 1
168
    /**
169
     * Executes the console command.
170 1
     *
171
     * @return mixed
172 1
     */
173 1
    public function handle()
174 1
    {
175 1
        $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 1
177 1
        $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 1
        $enabledOptions = Collection::make($this->options())->only([
180 1
            'hasBlocks',
181
            'hasTranslation',
182 1
            'hasSlug',
183 1
            'hasMedias',
184 1
            'hasFiles',
185 1
            'hasPosition',
186
            'hasRevisions',
187
        ])->filter(function ($enabled) {
188
            return $enabled;
189
        });
190 1
191
        if (count($enabledOptions) > 0) {
192 1
            $this->defaultsAnswserToNo = true;
193
        }
194 1
195 1
        $this->blockable = $this->checkOption('hasBlocks');
196
        $this->translatable = $this->checkOption('hasTranslation');
197
        $this->sluggable = $this->checkOption('hasSlug');
198
        $this->mediable = $this->checkOption('hasMedias');
199
        $this->fileable = $this->checkOption('hasFiles');
200
        $this->sortable = $this->checkOption('hasPosition');
201
        $this->revisionable = $this->checkOption('hasRevisions');
202
203
        $activeTraits = [
204 1
            $this->blockable,
205
            $this->translatable,
206 1
            $this->sluggable,
207 1
            $this->mediable,
208
            $this->fileable,
209 1
            $this->revisionable,
210
            $this->sortable,
211 1
        ];
212
213 1
        $modelName = Str::studly(Str::singular($moduleName));
214 1
215
        $this->createCapsuleNamespace(Str::studly($moduleName), $modelName);
216 1
217
        $this->createCapsulePath(Str::studly($moduleName), $modelName);
218 1
219 1
        $this->createMigration($moduleName);
220 1
        $this->createModels($modelName, $activeTraits);
221 1
        $this->createRepository($modelName, $activeTraits);
222
        $this->createController($moduleName, $modelName);
223
        $this->createRequest($modelName);
224 1
        $this->createViews($moduleName);
225 1
        $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
        $this->createSeed($moduleName);
227
228
        $this->info("Add Route::module('{$moduleName}'); to your admin routes file.");
229
        $this->info("Setup a new CMS menu item in config/twill-navigation.php:");
230
231
        $navTitle = Str::studly($moduleName);
232
233 1
        $this->info("
234 1
            '{$moduleName}' => [
235 1
                'title' => '{$navTitle}',
236 1
                'module' => true
237
            ]
238 1
        ");
239
240 1
        if ($this->isCapsule) {
241
            $this->info("Setup your new Capsule on config/twill.php:");
242 1
243
            $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 1
245
            $this->info("
246
                'capsules' => [
247
                    'name' => '{$this->capsule['name']}',
248
                    'enabled' => true
249
                ]
250
            ");
251
        }
252
253 1
        $this->info("Migrate your database.\n");
254
255 1
        $this->info("Enjoy.");
256
257 1
        $this->composer->dumpAutoloads();
258
    }
259 1
260 1
    /**
261
     * Creates a new module database migration file.
262 1
     *
263
     * @param string $moduleName
264 1
     * @return void
265 1
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
266 1
     */
267 1
    private function createMigration($moduleName = 'items')
268
    {
269
        $table = Str::snake($moduleName);
270 1
        $tableClassName = Str::studly($table);
271
272
        $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 1
274 1
        $migrationName = 'create_' . $table . '_tables';
275
276 1
        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
            $migrationPath = $this->databasePath() . '/migrations';
278 1
279
            $this->makeDir($migrationPath);
280 1
281
            $fullPath = $this->laravel['migration.creator']->create($migrationName, $migrationPath);
282
283 1
            $stub = str_replace(
284 1
                ['{{table}}', '{{singularTableName}}', '{{tableClassName}}'],
285
                [$table, Str::singular($table), $tableClassName],
286 1
                $this->files->get(__DIR__ . '/stubs/migration.stub')
287
            );
288 1
289
            if ($this->translatable) {
290 1
                $stub = preg_replace('/{{!hasTranslation}}[\s\S]+?{{\/!hasTranslation}}/', '', $stub);
291
            } else {
292
                $stub = str_replace([
293 1
                    '{{!hasTranslation}}',
294
                    '{{/!hasTranslation}}',
295 1
                ], '', $stub);
296 1
            }
297 1
298
            $stub = $this->renderStubForOption($stub, 'hasTranslation', $this->translatable);
299
            $stub = $this->renderStubForOption($stub, 'hasSlug', $this->sluggable);
300
            $stub = $this->renderStubForOption($stub, 'hasRevisions', $this->revisionable);
301 1
            $stub = $this->renderStubForOption($stub, 'hasPosition', $this->sortable);
302
303 1
            $stub = preg_replace('/\}\);[\s\S]+?Schema::create/', "});\n\n        Schema::create", $stub);
304
305 1
            $this->files->put($fullPath, $stub);
306
307 1
            $this->info("Migration created successfully! Add some fields!");
308 1
        }
309
    }
310
311 1
    /**
312 1
     * 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 1
     */
318 1
    private function createModels($modelName = 'Item', $activeTraits = [])
319 1
    {
320 1
        $modelClassName = $this->namespace('models', 'Models', $modelName);
321 1
322
        $modelsDir = $this->isCapsule ? $this->capsule['models_dir'] : 'Models';
323 1
324 1
        $this->makeTwillDirectory($modelsDir);
325 1
326 1
        if ($this->translatable) {
327
            $this->makeTwillDirectory($baseDir = $this->isCapsule ? $modelsDir : "{$modelsDir}/Translations");
328 1
329
            $modelTranslationClassName = $modelName . 'Translation';
330 1
331 1
            $stub = str_replace(
332
                ['{{modelTranslationClassName}}', '{{modelClassWithNamespace}}', '{{modelClassName}}', '{{namespace}}'],
333 1
                [$modelTranslationClassName, $modelClassName, $modelName, $this->namespace('models', 'Models\Translations')],
334
                $this->files->get(__DIR__ . '/stubs/model_translation.stub')
335 1
            );
336 1
337 1
            twill_put_stub(twill_path("{$baseDir}/" . $modelTranslationClassName . '.php'), $stub);
338 1
        }
339 1
340
        if ($this->sluggable) {
341
            $this->makeTwillDirectory($baseDir = $this->isCapsule ? $modelsDir : "{$modelsDir}/Slugs");
342
343
            $modelSlugClassName = $modelName . 'Slug';
344 1
345
            $stub = str_replace(
346
                ['{{modelSlugClassName}}', '{{modelClassWithNamespace}}', '{{modelName}}', '{{namespace}}'],
347
                [$modelSlugClassName, $modelClassName, Str::snake($modelName), $this->namespace('models', 'Models\Slugs')],
348
                $this->files->get(__DIR__ . '/stubs/model_slug.stub')
349
            );
350
351
            twill_put_stub(twill_path("{$baseDir}/" . $modelSlugClassName . '.php'), $stub);
352
        }
353
354
        if ($this->revisionable) {
355 1
            $this->makeTwillDirectory($baseDir = $this->isCapsule ? $modelsDir : "{$modelsDir}/Revisions");
356
357 1
            $modelRevisionClassName = $modelName . 'Revision';
358
359 1
            $stub = str_replace(
360
                ['{{modelRevisionClassName}}', '{{modelClassWithNamespace}}', '{{modelName}}', '{{namespace}}'],
361 1
                [$modelRevisionClassName, $modelClassName, Str::snake($modelName), $this->namespace('models', 'Models\Revisions')],
362
                $this->files->get(__DIR__ . '/stubs/model_revision.stub')
363 1
            );
364 1
365 1
            twill_put_stub(twill_path("{$baseDir}/" . $modelRevisionClassName . '.php'), $stub);
366
        }
367
368
        $activeModelTraits = [];
369 1
370
        foreach ($activeTraits as $index => $traitIsActive) {
371 1
            if ($traitIsActive) {
372
                !isset($this->modelTraits[$index]) ?: $activeModelTraits[] = $this->modelTraits[$index];
373 1
            }
374
        }
375 1
376
        $activeModelTraitsString = empty($activeModelTraits) ? '' : 'use ' . rtrim(implode(', ', $activeModelTraits), ', ') . ';';
377 1
378 1
        $activeModelTraitsImports = empty($activeModelTraits) ? '' : "use A17\Twill\Models\Behaviors\\" . implode(";\nuse A17\Twill\Models\Behaviors\\", $activeModelTraits) . ";";
379
380
        $activeModelImplements = $this->sortable ? 'implements Sortable' : '';
381
382
        if ($this->sortable) {
383
            $activeModelTraitsImports .= "\nuse A17\Twill\Models\Behaviors\Sortable;";
384
        }
385
386
        $stub = str_replace([
387
            '{{modelClassName}}',
388 1
            '{{modelTraits}}',
389
            '{{modelImports}}',
390 1
            '{{modelImplements}}',
391
            '{{namespace}}',
392 1
        ], [
393
            $modelName,
394 1
            $activeModelTraitsString,
395 1
            $activeModelTraitsImports,
396 1
            $activeModelImplements,
397 1
            $this->namespace('models', 'Models')
398
        ], $this->files->get(__DIR__ . '/stubs/model.stub'));
399
400 1
        $stub = $this->renderStubForOption($stub, 'hasTranslation', $this->translatable);
401
        $stub = $this->renderStubForOption($stub, 'hasSlug', $this->sluggable);
402 1
        $stub = $this->renderStubForOption($stub, 'hasMedias', $this->mediable);
403 1
        $stub = $this->renderStubForOption($stub, 'hasPosition', $this->sortable);
404
405
        twill_put_stub(twill_path("{$modelsDir}/" . $modelName . '.php'), $stub);
406
407
        $this->info("Models created successfully! Fill your fillables!");
408
    }
409
410
    private function renderStubForOption($stub, $option, $enabled)
411
    {
412 1
        if ($enabled) {
413
            $stub = str_replace([
414 1
                '{{' . $option . '}}',
415
                '{{/' . $option . '}}',
416 1
            ], '', $stub);
417
        } else {
418 1
            $stub = preg_replace('/{{' . $option . '}}[\s\S]+?{{\/' . $option . '}}/', '', $stub);
419
        }
420 1
421
        return $stub;
422 1
    }
423 1
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 1
    private function createRepository($modelName = 'Item', $activeTraits = [])
433
    {
434 1
        $modelsDir = $this->isCapsule ? $this->capsule['repositories_dir'] : 'Repositories';
435
436 1
        $modelClass = $this->isCapsule ? $this->capsule['model'] : "App\Models\\{$this->capsule['singular']}";
437
438 1
        $this->makeTwillDirectory($modelsDir);
439
440 1
        $repositoryClassName = $modelName . 'Repository';
441
442 1
        $activeRepositoryTraits = [];
443 1
444
        foreach ($activeTraits as $index => $traitIsActive) {
445 1
            if ($traitIsActive) {
446
                !isset($this->repositoryTraits[$index]) ?: $activeRepositoryTraits[] = $this->repositoryTraits[$index];
447 1
            }
448 1
        }
449
450
        $activeRepositoryTraitsString = empty($activeRepositoryTraits) ? '' : 'use ' . (empty($activeRepositoryTraits) ? "" : rtrim(implode(', ', $activeRepositoryTraits), ', ') . ';');
451
452
        $activeRepositoryTraitsImports = empty($activeRepositoryTraits) ? '' : "use A17\Twill\Repositories\Behaviors\\" . implode(";\nuse A17\Twill\Repositories\Behaviors\\", $activeRepositoryTraits) . ";";
453
454
        $stub = str_replace(
455
            ['{{repositoryClassName}}', '{{modelName}}', '{{repositoryTraits}}', '{{repositoryImports}}', '{{namespace}}', '{{modelClass}}'],
456
            [$repositoryClassName, $modelName, $activeRepositoryTraitsString, $activeRepositoryTraitsImports,$this->namespace('repositories', 'Repositories'), $modelClass],
457
            $this->files->get(__DIR__ . '/stubs/repository.stub')
458
        );
459
460
        twill_put_stub(twill_path("{$modelsDir}/" . $repositoryClassName . '.php'), $stub);
461
462
        $this->info("Repository created successfully! Control all the things!");
463
    }
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
    private function createController($moduleName = 'items', $modelName = 'Item')
474
    {
475
        $controllerClassName = $modelName . 'Controller';
476
477
        $dir = $this->isCapsule ? $this->capsule['controllers_dir'] : 'Http/Controllers/Admin';
478
479
        $this->makeTwillDirectory($dir);
480
481
        $stub = str_replace(
482
            ['{{moduleName}}', '{{controllerClassName}}', '{{namespace}}'],
483
            [$moduleName, $controllerClassName,$this->namespace('controllers', 'Http\Controllers\Admin')],
484
            $this->files->get(__DIR__ . '/stubs/controller.stub')
485
        );
486
487
        twill_put_stub(twill_path("{$dir}/" . $controllerClassName . '.php'), $stub);
488
489
        $this->info("Controller created successfully! Define your index/browser/form endpoints options!");
490
    }
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
    private function createRequest($modelName = 'Item')
500
    {
501
        $dir = $this->isCapsule ? $this->capsule['requests_dir'] : 'Http/Requests/Admin';
502
503
        $this->makeTwillDirectory($dir);
504
505
        $requestClassName = $modelName . 'Request';
506
507
        $stub = str_replace(
508
            ['{{requestClassName}}','{{namespace}}'],
509
            [$requestClassName,$this->namespace('requests', 'Http\Requests\Admin')],
510
            $this->files->get(__DIR__ . '/stubs/request.stub')
511
        );
512
513
        twill_put_stub(twill_path("{$dir}/" . $requestClassName . '.php'), $stub);
514
515
        $this->info("Form request created successfully! Add some validation rules!");
516
    }
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
    private function createViews($moduleName = 'items')
526
    {
527
        $viewsPath = $this->viewPath($moduleName);
528
529
        $this->makeTwillDirectory($viewsPath);
530
531
        $formView = $this->translatable ? 'form_translatable' : 'form';
532
533
        twill_put_stub($viewsPath . '/form.blade.php', $this->files->get(__DIR__ . '/stubs/' . $formView . '.blade.stub'));
534
535
        $this->info("Form view created successfully! Include your form fields using @formField directives!");
536
    }
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
    public function createRoutes()
546
    {
547
        $this->makeDir($this->capsule['routes_file']);
548
549
        $contents = str_replace(
550
            '{{moduleName}}',
551
            $this->capsule['module'],
552
            $this->files->get(__DIR__ . '/stubs/routes_admin.stub')
553
        );
554
555
        twill_put_stub($this->capsule['routes_file'], $contents);
556
557
        $this->info("Routes file created successfully!");
558
    }
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
    private function createSeed($moduleName = 'items')
568
    {
569
        $this->makeTwillDirectory($this->capsule['seeds_psr4_path']);
570
571
        $stub = $this->files->get(__DIR__ . '/stubs/database_seeder.stub');
572
573
        $stub = str_replace('{moduleName}', $this->capsule['plural'], $stub);
574
575
        $this->files->put("{$this->capsule['seeds_psr4_path']}/DatabaseSeeder.php", $stub);
576
577
        $this->info("Seed created successfully!");
578
    }
579
580
    private function checkOption($option)
581
    {
582
        if ($this->option($option) || $this->option('all')) {
583
            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
    public function createCapsulePath($moduleName, $modelName)
600
    {
601
        if (!$this->isCapsule) {
602
            $this->moduleBasePath = base_path();
603
604
            return;
605
        }
606
607
        $this->checkCapsuleDirectory(
608
            $this->moduleBasePath = config('twill.capsules.path')."/{$moduleName}"
609
        );
610
611
        $this->makeDir($this->moduleBasePath);
612
    }
613
614
    public function createCapsuleNamespace($module, $model)
615
    {
616
        $base = config('twill.capsules.namespace');
617
618
        $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
    }
620
621
    public function databasePath($path = '')
622
    {
623
        if (!$this->isCapsule) {
624
            return database_path($path);
625
        }
626
627
        return "{$this->moduleBasePath}/database" . (filled($path) ? "/{$path}" : '');
628
    }
629
630
    public function makeDir($dir)
631
    {
632
        $info = pathinfo($dir);
633
634
        $dir = isset($info['extension']) ? $info['dirname'] : $dir;
635
636
        if (!is_dir($dir))
637
        {
638
            mkdir($dir, 0755, true);
639
        }
640
641
        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
    }
647
648
    public function makeTwillDirectory($path)
649
    {
650
        make_twill_directory($path);
651
    }
652
653
    public function namespace($type, $suffix, $class = null)
654
    {
655
        $class = (filled($class) ? "\\$class" : '');
656
657
        if (!$this->isCapsule) {
658
            return "App\\{$suffix}{$class}";
659
        }
660
661
        return $this->capsule[$type] . $class;
662
    }
663
664
    public function viewPath($moduleName)
665
    {
666
        if (!$this->isCapsule) {
667
            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
        $this->makeDir($dir = "{$this->moduleBasePath}/resources/views/admin");
671
672
        return $dir;
673
    }
674
}
675