Passed
Push — master ( 08e0de...df0894 )
by Gombos
03:08
created

CreateSettingsFieldForModel::handle()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 43
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 26
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 43
ccs 27
cts 27
cp 1
crap 4
rs 9.504
1
<?php
2
3
namespace Glorand\Model\Settings\Console;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Filesystem\Filesystem;
7
use Illuminate\Support\Facades\Schema;
8
use Illuminate\Support\Str;
9
10
class CreateSettingsFieldForModel extends Command
11
{
12
    /** @var string */
13
    protected $signature = 'model-settings:model-settings-field';
14
15
    /** @var string */
16
    protected $description = 'Create migration for the (update) selected table, adding settings field';
17
18
    /**
19
     * @param \Illuminate\Filesystem\Filesystem $file
20
     * @return bool
21
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
22
     */
23 12
    public function handle(Filesystem $file)
24
    {
25 12
        $table = $this->ask('What is the name of the table?');
26 12
        $table = strtolower(Str::snake(trim($table)));
27 12
        if (empty($table)) {
28 3
            $this->error('The name of the table is required!');
29
30 3
            return 1;
31
        }
32 9
        if (!Schema::hasTable($table)) {
33 3
            $this->error('Unable to find table "' . $table . '" on the current DB!');
34
35 3
            return 2;
36
        }
37
38 6
        $defaultFieldName = config('model_settings.settings_field_name');
39 6
        $fieldName = $this->ask(
40 6
            'What is the name of the settings field name?',
41 2
            $defaultFieldName
42
        );
43 6
        $fieldName = strtolower(Str::snake(trim($fieldName)));
44
45 6
        if (Schema::hasColumn($table, $fieldName)) {
46 3
            $this->error('Field "' . $fieldName . '" already exists on table "' . $table . '"');
47
48 3
            return 3;
49
        }
50
51 3
        $fileName = date('Y_m_d_His') . '_update_' . $table . '_table_add_' . $fieldName . '.php';
52 3
        $path = database_path('migrations') . '/' . $fileName;
53 3
        $className = 'Update' . ucfirst($table) . 'TableAdd' . ucfirst(Str::camel($fieldName));
54
55
56 3
        $stub = $file->get(__DIR__ . '/../../stubs/create_settings_field.stub');
57 3
        $stub = str_replace('DummyClass', $className, $stub);
58 3
        $stub = str_replace('DummyTable', $table, $stub);
59 3
        $stub = str_replace('settingsFieldName', $fieldName, $stub);
60
61 3
        $file->replace($path, $stub);
62
63 3
        $this->line("<info>Created Migration:</info> {$fileName}");
64
65 3
        return 0;
66
    }
67
}
68