Passed
Push — master ( 34ffd7...1a2918 )
by Biao
07:32 queued 04:04
created

LaravelSCommand::publish()   C

Complexity

Conditions 12
Paths 24

Size

Total Lines 61
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 2 Features 0
Metric Value
cc 12
eloc 41
c 8
b 2
f 0
nc 24
nop 0
dl 0
loc 61
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
0 ignored issues
show
Coding Style introduced by
Missing file doc comment
Loading history...
3
namespace Hhxsv5\LaravelS\Illuminate;
4
5
use Illuminate\Console\Command;
0 ignored issues
show
Bug introduced by
The type Illuminate\Console\Command was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Illuminate\Support\Arr;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Arr was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
8
class LaravelSCommand extends Command
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class LaravelSCommand
Loading history...
9
{
10
    protected $signature = 'laravels {action? : publish|config|info}
11
    {--d|daemonize : Run as a daemon}
12
    {--i|ignore : Ignore checking PID file of Master process}
13
    {--x=|x-version= : The version(branch) of the current project, stored in $_ENV/$_SERVER}';
14
15
    protected $description = 'LaravelS console tool';
16
17
    public function fire()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function fire()
Loading history...
18
    {
19
        $this->handle();
20
    }
21
22
    public function handle()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function handle()
Loading history...
23
    {
24
        $action = (string)$this->argument('action');
25
        switch ($action) {
26
            case 'publish':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
27
                $this->publish();
28
                break;
29
            case 'config':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
30
                $this->prepareConfig();
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
31
            case 'info':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
32
                $this->showInfo();
33
                break;
34
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
35
                $this->info(sprintf('Usage: [%s] ./artisan laravels publish|config|info', PHP_BINARY));
36
                if (in_array($action, ['start', 'stop', 'restart', 'reload'], true)) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
37
                    $this->error(sprintf(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
38
                        'The "%s" command has been migrated to "bin/laravels", %ssee https://github.com/hhxsv5/laravel-s#run',
39
                        $action,
40
                        file_exists(base_path('bin/laravels')) ? '' : 'please run `php artisan laravels publish` first, '
0 ignored issues
show
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
                        file_exists(/** @scrutinizer ignore-call */ base_path('bin/laravels')) ? '' : 'please run `php artisan laravels publish` first, '
Loading history...
41
                    ));
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
42
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
43
                break;
44
        }
45
    }
46
47
    protected function isLumen()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function isLumen()
Loading history...
48
    {
49
        return stripos($this->getApplication()->getVersion(), 'Lumen') !== false;
50
    }
51
52
    protected function loadConfig()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function loadConfig()
Loading history...
53
    {
54
        // Load configuration laravel.php manually for Lumen
55
        $basePath = config('laravels.laravel_base_path') ?: base_path();
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

55
        $basePath = /** @scrutinizer ignore-call */ config('laravels.laravel_base_path') ?: base_path();
Loading history...
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

55
        $basePath = config('laravels.laravel_base_path') ?: /** @scrutinizer ignore-call */ base_path();
Loading history...
56
        if ($this->isLumen() && file_exists($basePath . '/config/laravels.php')) {
57
            $this->getLaravel()->configure('laravels');
58
        }
59
    }
60
61
    protected function showInfo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showInfo()
Loading history...
62
    {
63
        $this->showLogo();
64
        $this->showComponents();
65
        $this->showProtocols();
66
        $this->comment('>>> Feedback: <options=underscore>https://github.com/hhxsv5/laravel-s</>');
67
    }
68
69
    protected function showLogo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showLogo()
Loading history...
70
    {
71
        static $logo = <<<EOS
72
 _                               _  _____ 
73
| |                             | |/ ____|
74
| |     __ _ _ __ __ ___   _____| | (___  
75
| |    / _` | '__/ _` \ \ / / _ \ |\___ \ 
76
| |___| (_| | | | (_| |\ V /  __/ |____) |
77
|______\__,_|_|  \__,_| \_/ \___|_|_____/ 
78
                                           
79
EOS;
80
        $this->info($logo);
81
        $this->info('Speed up your Laravel/Lumen');
82
    }
83
84
    protected function showComponents()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showComponents()
Loading history...
85
    {
86
        $this->comment('>>> Components');
87
        $laravelSVersion = '-';
88
        $cfg = file_exists(base_path('composer.lock')) ? json_decode(file_get_contents(base_path('composer.lock')), true) : [];
0 ignored issues
show
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

88
        $cfg = file_exists(/** @scrutinizer ignore-call */ base_path('composer.lock')) ? json_decode(file_get_contents(base_path('composer.lock')), true) : [];
Loading history...
89
        if (isset($cfg['packages'])) {
90
            $packages = array_merge($cfg['packages'], Arr::get($cfg, 'packages-dev', []));
91
            foreach ($packages as $package) {
92
                if (isset($package['name']) && $package['name'] === 'hhxsv5/laravel-s') {
93
                    $laravelSVersion = ltrim($package['version'], 'vV');
94
                    break;
95
                }
96
            }
97
        }
98
        $this->table(['Component', 'Version'], [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
99
            [
100
                'PHP',
101
                phpversion(),
102
            ],
103
            [
104
                'Swoole',
105
                swoole_version(),
0 ignored issues
show
Bug introduced by
Are you sure the usage of swoole_version() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
106
            ],
107
            [
108
                'LaravelS',
109
                $laravelSVersion,
110
            ],
111
            [
112
                $this->getApplication()->getName() . ' [<info>' . env('APP_ENV', config('app.env')) . '</info>]',
0 ignored issues
show
Bug introduced by
The function env was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
                $this->getApplication()->getName() . ' [<info>' . /** @scrutinizer ignore-call */ env('APP_ENV', config('app.env')) . '</info>]',
Loading history...
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
                $this->getApplication()->getName() . ' [<info>' . env('APP_ENV', /** @scrutinizer ignore-call */ config('app.env')) . '</info>]',
Loading history...
113
                $this->getApplication()->getVersion(),
114
            ],
115
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
116
    }
117
118
    protected function showProtocols()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showProtocols()
Loading history...
119
    {
120
        $this->comment('>>> Protocols');
121
122
        $config = unserialize(file_get_contents($this->getConfPath()));
123
        $socketType = isset($config['server']['socket_type']) ? $config['server']['socket_type'] : SWOOLE_SOCK_TCP;
124
        if (in_array($socketType, [SWOOLE_SOCK_UNIX_DGRAM, SWOOLE_SOCK_UNIX_STREAM])) {
125
            $listenAt = $config['server']['listen_ip'];
126
        } else {
127
            $listenAt = sprintf('%s:%s', $config['server']['listen_ip'], $config['server']['listen_port']);
128
        }
129
130
        $tableRows = [
131
            [
132
                'Main HTTP',
133
                '<info>On</info>',
134
                $this->getApplication()->getName(),
135
                $listenAt,
136
            ],
137
        ];
138
        if (!empty($config['server']['websocket']['enable'])) {
139
            $tableRows [] = [
140
                'Main WebSocket',
141
                '<info>On</info>',
142
                $config['server']['websocket']['handler'],
143
                $listenAt,
144
            ];
145
        }
146
147
        $socketTypeNames = [
148
            SWOOLE_SOCK_TCP         => 'TCP IPV4 Socket',
149
            SWOOLE_SOCK_TCP6        => 'TCP IPV6 Socket',
150
            SWOOLE_SOCK_UDP         => 'UDP IPV4 Socket',
151
            SWOOLE_SOCK_UDP6        => 'TCP IPV6 Socket',
152
            SWOOLE_SOCK_UNIX_DGRAM  => 'Unix Socket Dgram',
153
            SWOOLE_SOCK_UNIX_STREAM => 'Unix Socket Stream',
154
        ];
155
        $sockets = isset($config['server']['sockets']) ? $config['server']['sockets'] : [];
156
        foreach ($sockets as $key => $socket) {
157
            if (isset($socket['enable']) && !$socket['enable']) {
158
                continue;
159
            }
160
161
            $name = 'Port#' . $key . ' ';
162
            $name .= isset($socketTypeNames[$socket['type']]) ? $socketTypeNames[$socket['type']] : 'Unknown socket';
163
            $tableRows [] = [
164
                $name,
165
                '<info>On</info>',
166
                $socket['handler'],
167
                sprintf('%s:%s', $socket['host'], $socket['port']),
168
            ];
169
        }
170
        $this->table(['Protocol', 'Status', 'Handler', 'Listen At'], $tableRows);
171
    }
172
173
    protected function prepareConfig()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function prepareConfig()
Loading history...
174
    {
175
        $this->loadConfig();
176
177
        $svrConf = config('laravels');
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

177
        $svrConf = /** @scrutinizer ignore-call */ config('laravels');
Loading history...
178
179
        $this->preSet($svrConf);
180
181
        $ret = $this->preCheck($svrConf);
182
        if ($ret !== 0) {
183
            return $ret;
184
        }
185
186
        $laravelConf = [
187
            'root_path'           => $svrConf['laravel_base_path'],
188
            'static_path'         => $svrConf['swoole']['document_root'],
189
            'cleaners'            => array_unique((array)Arr::get($svrConf, 'cleaners', [])),
190
            'register_providers'  => array_unique((array)Arr::get($svrConf, 'register_providers', [])),
191
            'destroy_controllers' => Arr::get($svrConf, 'destroy_controllers', []),
192
            'is_lumen'            => $this->isLumen(),
193
            '_SERVER'             => $_SERVER,
194
            '_ENV'                => $_ENV,
195
        ];
196
197
        $config = ['server' => $svrConf, 'laravel' => $laravelConf];
198
        return file_put_contents($this->getConfPath(), serialize($config)) > 0 ? 0 : 1;
199
    }
200
201
    protected function getConfPath()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getConfPath()
Loading history...
202
    {
203
        return base_path('storage/laravels.conf');
0 ignored issues
show
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

203
        return /** @scrutinizer ignore-call */ base_path('storage/laravels.conf');
Loading history...
204
    }
205
206
    protected function preSet(array &$svrConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function preSet()
Loading history...
207
    {
208
        if (!isset($svrConf['enable_gzip'])) {
209
            $svrConf['enable_gzip'] = false;
210
        }
211
        if (empty($svrConf['laravel_base_path'])) {
212
            $svrConf['laravel_base_path'] = base_path();
0 ignored issues
show
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

212
            $svrConf['laravel_base_path'] = /** @scrutinizer ignore-call */ base_path();
Loading history...
213
        }
214
        if (empty($svrConf['process_prefix'])) {
215
            $svrConf['process_prefix'] = $svrConf['laravel_base_path'];
216
        }
217
        if ($this->option('ignore')) {
218
            $svrConf['ignore_check_pid'] = true;
219
        } elseif (!isset($svrConf['ignore_check_pid'])) {
220
            $svrConf['ignore_check_pid'] = false;
221
        }
222
        if (empty($svrConf['swoole']['document_root'])) {
223
            $svrConf['swoole']['document_root'] = $svrConf['laravel_base_path'] . '/public';
224
        }
225
        if ($this->option('daemonize')) {
226
            $svrConf['swoole']['daemonize'] = true;
227
        } elseif (!isset($svrConf['swoole']['daemonize'])) {
228
            $svrConf['swoole']['daemonize'] = false;
229
        }
230
        if (empty($svrConf['swoole']['pid_file'])) {
231
            $svrConf['swoole']['pid_file'] = storage_path('laravels.pid');
0 ignored issues
show
Bug introduced by
The function storage_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

231
            $svrConf['swoole']['pid_file'] = /** @scrutinizer ignore-call */ storage_path('laravels.pid');
Loading history...
232
        }
233
        if (empty($svrConf['timer']['max_wait_time'])) {
234
            $svrConf['timer']['max_wait_time'] = 5;
235
        }
236
237
        // Set X-Version
238
        $xVersion = (string)$this->option('x-version');
239
        if ($xVersion !== '') {
240
            $_SERVER['X_VERSION'] = $_ENV['X_VERSION'] = $xVersion;
241
        }
242
        return 0;
243
    }
244
245
    protected function preCheck(array $svrConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function preCheck()
Loading history...
246
    {
247
        if (!empty($svrConf['enable_gzip']) && version_compare(swoole_version(), '4.1.0', '>=')) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of swoole_version() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
248
            $this->error('enable_gzip is DEPRECATED since Swoole 4.1.0, set http_compression of Swoole instead, http_compression is disabled by default.');
249
            $this->info('If there is a proxy server like Nginx, suggest that enable gzip in Nginx and disable gzip in Swoole, to avoid the repeated gzip compression for response.');
250
            return 1;
251
        }
252
        if (!empty($svrConf['events'])) {
253
            if (empty($svrConf['swoole']['task_worker_num']) || $svrConf['swoole']['task_worker_num'] <= 0) {
254
                $this->error('Asynchronous event listening needs to set task_worker_num > 0');
255
                return 1;
256
            }
257
        }
258
        return 0;
259
    }
260
261
262
    public function publish()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function publish()
Loading history...
263
    {
264
        $basePath = config('laravels.laravel_base_path') ?: base_path();
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

264
        $basePath = /** @scrutinizer ignore-call */ config('laravels.laravel_base_path') ?: base_path();
Loading history...
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

264
        $basePath = config('laravels.laravel_base_path') ?: /** @scrutinizer ignore-call */ base_path();
Loading history...
265
        $configPath = $basePath . '/config/laravels.php';
266
        $todoList = [
267
            [
268
                'from' => realpath(__DIR__ . '/../../config/laravels.php'),
269
                'to'   => $configPath,
270
                'mode' => 0644,
271
            ],
272
            [
273
                'from' => realpath(__DIR__ . '/../../bin/laravels'),
274
                'to'   => $basePath . '/bin/laravels',
275
                'mode' => 0755,
276
                'link' => true,
277
            ],
278
            [
279
                'from' => realpath(__DIR__ . '/../../bin/fswatch'),
280
                'to'   => $basePath . '/bin/fswatch',
281
                'mode' => 0755,
282
                'link' => true,
283
            ],
284
            [
285
                'from' => realpath(__DIR__ . '/../../bin/inotify'),
286
                'to'   => $basePath . '/bin/inotify',
287
                'mode' => 0755,
288
                'link' => true,
289
            ],
290
        ];
291
        if (file_exists($configPath)) {
292
            $choice = $this->anticipate($configPath . ' already exists, do you want to override it ? Y/N',
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
293
                ['Y', 'N'],
294
                'N'
295
            );
296
            if (!$choice || strtoupper($choice) !== 'Y') {
297
                array_shift($todoList);
298
            }
299
        }
300
301
        foreach ($todoList as $todo) {
302
            $toDir = dirname($todo['to']);
303
            if (!is_dir($toDir) && !mkdir($toDir, 0755, true) && !is_dir($toDir)) {
304
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $toDir));
305
            }
306
            if (file_exists($todo['to'])) {
307
                unlink($todo['to']);
308
            }
309
            $operation = 'Copied';
310
            if (empty($todo['link'])) {
311
                copy($todo['from'], $todo['to']);
312
            } else {
313
                if (@link($todo['from'], $todo['to'])) {
314
                    $operation = 'Linked';
315
                } else {
316
                    copy($todo['from'], $todo['to']);
317
                }
318
            }
319
            chmod($todo['to'], $todo['mode']);
320
            $this->line("<info>{$operation} file</info> <comment>[{$todo['from']}]</comment> <info>To</info> <comment>[{$todo['to']}]</comment>");
321
        }
322
        return 0;
323
    }
324
}
325