Completed
Push — master ( d64bdd...237512 )
by wen
13:09
created

ComponentMakeCommand::getViewColumns()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
3
namespace Sco\Admin\Console;
4
5
use Doctrine\DBAL\Schema\Column;
6
use Illuminate\Console\GeneratorCommand;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Str;
9
use InvalidArgumentException;
10
use Sco\Admin\Facades\AdminElement;
11
use Symfony\Component\Console\Input\InputOption;
12
13
class ComponentMakeCommand extends GeneratorCommand
14
{
15
    /**
16
     * The console command name.
17
     *
18
     * @var string
19
     */
20
    protected $name = 'make:component';
21
22
    /**
23
     * The console command description.
24
     *
25
     * @var string
26
     */
27
    protected $description = 'Create a new component class(ScoAdmin)';
28
29
    /**
30
     * The type of class being generated.
31
     *
32
     * @var string
33
     */
34
    protected $type = 'Component';
35
36
    /**
37
     * Execute the console command.
38
     *
39
     * @return void
40
     */
41
    public function handle()
42
    {
43
        if (parent::handle() === false && !$this->option('force')) {
44
            return;
45
        }
46
47
        if ($this->option('observer')) {
48
            $this->createObserver();
49
        }
50
    }
51
52
    /**
53
     * Create a new permission observer for the component
54
     */
55
    protected function createObserver()
56
    {
57
        $observerClass = $this->parseClass($this->option('observer'));
0 ignored issues
show
Bug introduced by
It seems like $this->option('observer') targeting Illuminate\Console\Command::option() can also be of type array; however, Sco\Admin\Console\Compon...keCommand::parseClass() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
58
59
        //$this->info('observer:' . $observerClass);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
60
61
        $this->call('make:observer', [
62
            'name' => $observerClass,
63
        ]);
64
    }
65
66
    /**
67
     * Get the fully-qualified class name.
68
     *
69
     * @param string $class
70
     *
71
     * @return string
72
     */
73
    protected function parseClass($class)
74
    {
75
        if (preg_match('([^A-Za-z0-9_/\\\\])', $class)) {
76
            throw new InvalidArgumentException('Model name contains invalid characters.');
77
        }
78
79
        $class = trim(str_replace('/', '\\', $class), '\\');
80
81
        if (!Str::startsWith($class, $rootNamespace = $this->laravel->getNamespace())) {
82
            $class = $rootNamespace . $class;
83
        }
84
85
        return $class;
86
    }
87
88
    /**
89
     * Get the stub file for the generator.
90
     *
91
     * @return string
92
     */
93
    protected function getStub()
94
    {
95
        return __DIR__ . '/stubs/component.stub';
96
    }
97
98
    /**
99
     * Build the class with the given name.
100
     *
101
     * @param string $name
102
     *
103
     * @return string
104
     */
105
    protected function buildClass($name)
106
    {
107
        $observer = $this->option('observer')
108
            ? $this->parseClass($this->option('observer'))
0 ignored issues
show
Bug introduced by
It seems like $this->option('observer') targeting Illuminate\Console\Command::option() can also be of type array; however, Sco\Admin\Console\Compon...keCommand::parseClass() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
109
            : \Sco\Admin\Component\Observer::class;
110
111
        $model = $this->option('model')
112
            ? $this->parseClass($this->option('model'))
0 ignored issues
show
Bug introduced by
It seems like $this->option('model') targeting Illuminate\Console\Command::option() can also be of type array; however, Sco\Admin\Console\Compon...keCommand::parseClass() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
113
            : '';
114
115
        $columns = $this->getViewColumns($model);
116
        // $elements = $this->getFormElements($model);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
117
118
119
        return str_replace(
120
            ['DummyObserver', 'DummyModel', 'DummyColumns'],
121
            [$observer, $model, $columns],
122
            parent::buildClass($name)
123
        );
124
    }
125
126
    protected function getViewColumns($model)
127
    {
128
        $columns = $this->getTableColumns($model);
129
        if (!$columns) {
130
            return ;
131
        }
132
133
        $list    = [];
134
        foreach ($columns as $column) {
135
            $list[] = $this->buildColumn($column);
136
        }
137
        return implode("\n", $list);
138
    }
139
140
    protected function buildColumn(Column $column)
141
    {
142
        $title = $column->getComment() ?? camel_case($column->getName());
143
144
        return sprintf(
145
            "            AdminColumn::%s('%s', '%s'),",
146
            'text',
147
            $column->getName(),
148
            $title
149
        );
150
    }
151
152
    protected function getFormElements($model)
153
    {
154
        $columns = $this->getTableColumns($model);
0 ignored issues
show
Unused Code introduced by
$columns is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
155
156
157
    }
158
159
    protected function getTableColumns($class)
160
    {
161
        if (empty($class)) {
162
            return;
163
        }
164
165
        if (!class_exists($class)) {
166
            return;
167
        }
168
169
        $model = new $class();
170
        if (!($model instanceof Model)) {
171
            return;
172
        }
173
        $schema = $model->getConnection()->getDoctrineSchemaManager();
174
175
        $table = $model->getConnection()->getTablePrefix() . $model->getTable();
176
177
        return $schema->listTableColumns($table);
178
    }
179
180
    /**
181
     * Get the default namespace for the class.
182
     *
183
     * @param  string $rootNamespace
184
     *
185
     * @return string
186
     */
187
    protected function getDefaultNamespace($rootNamespace)
188
    {
189
        return $rootNamespace . '\Components';
190
    }
191
192
    /**
193
     * Get the console command options.
194
     *
195
     * @return array
196
     */
197
    protected function getOptions()
198
    {
199
        return [
200
            [
201
                'observer', 'o', InputOption::VALUE_OPTIONAL,
202
                'Generate a new access observer for the component.',
203
            ],
204
            [
205
                'force', null, InputOption::VALUE_NONE,
206
                'Generate the class even if the component already exists.',
207
            ],
208
            [
209
                'model', 'm', InputOption::VALUE_OPTIONAL,
210
                'Generate a model for the component.',
211
            ],
212
        ];
213
    }
214
}
215