Completed
Push — master ( 59e60c...053593 )
by Song
02:38 queued 11s
created

MakeCommand::getNameInput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Console;
4
5
use Illuminate\Console\GeneratorCommand;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Str;
8
9
class MakeCommand extends GeneratorCommand
10
{
11
    /**
12
     * The console command name.
13
     *
14
     * @var string
15
     */
16
    protected $signature = 'admin:make {name}
17
        {--model=}
18
        {--title=}
19
        {--stub= : Path to the custom stub file. }
20
        {--namespace=}
21
        {--O|output}';
22
23
    /**
24
     * The console command description.
25
     *
26
     * @var string
27
     */
28
    protected $description = 'Make admin controller';
29
30
    /**
31
     * @var ResourceGenerator
32
     */
33
    protected $generator;
34
35
    /**
36
     * @var string
37
     */
38
    protected $controllerName;
39
40
    /**
41
     * @var string
42
     */
43
    protected $modelName;
44
45
    /**
46
     * Execute the console command.
47
     *
48
     * @return void
49
     */
50
    public function handle()
51
    {
52
        $this->modelName      = $this->getModelName();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getModelName() can also be of type array or boolean. However, the property $modelName is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
53
        $this->controllerName = $this->getControllerName();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getControllerName() can also be of type array. However, the property $controllerName is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
54
55
        if (!$this->modelExists()) {
56
            $this->error('Model does not exists !');
57
58
            return false;
59
        }
60
61
        $stub = $this->option('stub');
62
63
        if ($stub and !is_file($stub)) {
64
            $this->error('The stub file dose not exist.');
65
66
            return false;
67
        }
68
69
        $this->generator = new ResourceGenerator($this->modelName);
70
71
        if ($this->option('output')) {
72
            return $this->output($this->modelName);
73
        }
74
75
        if (parent::handle() !== false) {
76
            $path = Str::plural(Str::kebab(class_basename($this->modelName)));
77
78
            $this->line('');
79
            $this->comment('Add the following route to app/Admin/routes.php:');
80
            $this->line('');
81
            $this->info("    \$router->resource('{$path}', {$this->controllerName}::class);");
82
            $this->line('');
83
        }
84
    }
85
86
    /**
87
     * @return array|string|null
88
     */
89
    protected function getControllerName()
90
    {
91
        return $this->argument('name');
92
    }
93
94
    /**
95
     * @return array|string|null
96
     */
97
    protected function getModelName()
98
    {
99
        return $this->option('model');
100
    }
101
102
    /**
103
     * @return array|bool|string|null
104
     * @throws \ReflectionException
105
     */
106
    protected function getTitle()
107
    {
108
        if ($title = $this->option('title')) {
109
            return $title;
110
        }
111
112
        return __((new \ReflectionClass($this->modelName))->getShortName());
113
    }
114
115
    /**
116
     * @param string $modelName
117
     */
118
    protected function output($modelName)
119
    {
120
        $this->alert("laravel-admin controller code for model [{$modelName}]");
121
122
        $this->info($this->generator->generateGrid());
123
        $this->info($this->generator->generateShow());
124
        $this->info($this->generator->generateForm());
125
    }
126
127
    /**
128
     * Determine if the model is exists.
129
     *
130
     * @return bool
131
     */
132
    protected function modelExists()
133
    {
134
        if (empty($this->modelName)) {
135
            return true;
136
        }
137
138
        return class_exists($this->modelName) && is_subclass_of($this->modelName, Model::class);
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Illuminate\Database\Eloquent\Model::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
139
    }
140
141
    /**
142
     * Replace the class name for the given stub.
143
     *
144
     * @param string $stub
145
     * @param string $name
146
     *
147
     * @return string
148
     */
149
    protected function replaceClass($stub, $name)
150
    {
151
        $stub = parent::replaceClass($stub, $name);
152
153
        return str_replace(
154
            [
155
                'DummyModelNamespace',
156
                'DummyTitle',
157
                'DummyModel',
158
                'DummyGrid',
159
                'DummyShow',
160
                'DummyForm',
161
            ],
162
            [
163
                $this->modelName,
164
                $this->getTitle(),
165
                class_basename($this->modelName),
166
                $this->indentCodes($this->generator->generateGrid()),
167
                $this->indentCodes($this->generator->generateShow()),
168
                $this->indentCodes($this->generator->generateForm()),
169
            ],
170
            $stub
171
        );
172
    }
173
174
    /**
175
     * @param string $code
176
     *
177
     * @return string
178
     */
179
    protected function indentCodes($code)
180
    {
181
        $indent = str_repeat(' ', 8);
182
183
        return rtrim($indent.preg_replace("/\r\n/", "\r\n{$indent}", $code));
184
    }
185
186
    /**
187
     * Get the stub file for the generator.
188
     *
189
     * @return string
190
     */
191
    protected function getStub()
192
    {
193
        if ($stub = $this->option('stub')) {
194
            return $stub;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $stub; (string|array|boolean) is incompatible with the return type declared by the abstract method Illuminate\Console\GeneratorCommand::getStub of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
195
        }
196
197
        if ($this->modelName) {
198
            return __DIR__.'/stubs/controller.stub';
199
        }
200
201
        return __DIR__.'/stubs/blank.stub';
202
    }
203
204
    /**
205
     * Get the default namespace for the class.
206
     *
207
     * @param string $rootNamespace
208
     *
209
     * @return string
210
     */
211
    protected function getDefaultNamespace($rootNamespace)
212
    {
213
        if ($namespace = $this->option('namespace')) {
214
            return $namespace;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $namespace; (string|array|boolean) is incompatible with the return type documented by Encore\Admin\Console\Mak...nd::getDefaultNamespace of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
215
        }
216
217
        return config('admin.route.namespace');
218
    }
219
220
    /**
221
     * Get the desired class name from the input.
222
     *
223
     * @return string
224
     */
225
    protected function getNameInput()
226
    {
227
        $this->type = $this->qualifyClass($this->controllerName);
228
229
        return $this->controllerName;
230
    }
231
}
232