Passed
Pull Request — 2.x (#729)
by Quentin
05:28
created

ModuleMake::makeTwillDirectory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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