Passed
Push — master ( bab4d5...6a4c6b )
by Biao
02:56
created

LaravelSCommand::showComponents()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 19
c 1
b 0
f 0
nc 8
nop 0
dl 0
loc 31
rs 9.0111
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
            case 'info':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
31
                $this->prepareConfig();
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
        $lockFile = base_path('composer.lock');
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
        $lockFile = /** @scrutinizer ignore-call */ base_path('composer.lock');
Loading history...
89
        $cfg = file_exists($lockFile) ? json_decode(file_get_contents($lockFile), true) : [];
90
        if (isset($cfg['packages'])) {
91
            $packages = array_merge($cfg['packages'], Arr::get($cfg, 'packages-dev', []));
92
            foreach ($packages as $package) {
93
                if (isset($package['name']) && $package['name'] === 'hhxsv5/laravel-s') {
94
                    $laravelSVersion = ltrim($package['version'], 'vV');
95
                    break;
96
                }
97
            }
98
        }
99
        $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...
100
            [
101
                'PHP',
102
                PHP_VERSION,
103
            ],
104
            [
105
                'Swoole',
106
                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...
107
            ],
108
            [
109
                'LaravelS',
110
                $laravelSVersion,
111
            ],
112
            [
113
                $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

113
                $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

113
                $this->getApplication()->getName() . ' [<info>' . env('APP_ENV', /** @scrutinizer ignore-call */ config('app.env')) . '</info>]',
Loading history...
114
                $this->getApplication()->getVersion(),
115
            ],
116
        ]);
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...
117
    }
118
119
    protected function showProtocols()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showProtocols()
Loading history...
120
    {
121
        $this->comment('>>> Protocols');
122
123
        $config = unserialize((string)file_get_contents($this->getConfigPath()));
124
        $ssl = isset($config['server']['swoole']['ssl_key_file'], $config['server']['swoole']['ssl_cert_file']);
125
        $socketType = isset($config['server']['socket_type']) ? $config['server']['socket_type'] : SWOOLE_SOCK_TCP;
126
        if (in_array($socketType, [SWOOLE_SOCK_UNIX_DGRAM, SWOOLE_SOCK_UNIX_STREAM])) {
127
            $listenAt = $config['server']['listen_ip'];
128
        } else {
129
            $listenAt = sprintf('%s:%s', $config['server']['listen_ip'], $config['server']['listen_port']);
130
        }
131
132
        $tableRows = [
133
            [
134
                'Main HTTP',
135
                '<info>On</info>',
136
                $this->getApplication()->getName(),
137
                sprintf('%s://%s', $ssl ? 'https' : 'http', $listenAt),
138
            ],
139
        ];
140
        if (!empty($config['server']['websocket']['enable'])) {
141
            $tableRows [] = [
142
                'Main WebSocket',
143
                '<info>On</info>',
144
                $config['server']['websocket']['handler'],
145
                sprintf('%s://%s', $ssl ? 'wss' : 'ws', $listenAt),
146
            ];
147
        }
148
149
        $socketTypeNames = [
150
            SWOOLE_SOCK_TCP         => 'TCP IPV4 Socket',
151
            SWOOLE_SOCK_TCP6        => 'TCP IPV6 Socket',
152
            SWOOLE_SOCK_UDP         => 'UDP IPV4 Socket',
153
            SWOOLE_SOCK_UDP6        => 'TCP IPV6 Socket',
154
            SWOOLE_SOCK_UNIX_DGRAM  => 'Unix Socket Dgram',
155
            SWOOLE_SOCK_UNIX_STREAM => 'Unix Socket Stream',
156
        ];
157
        $sockets = isset($config['server']['sockets']) ? $config['server']['sockets'] : [];
158
        foreach ($sockets as $key => $socket) {
159
            if (isset($socket['enable']) && !$socket['enable']) {
160
                continue;
161
            }
162
163
            $name = 'Port#' . $key . ' ';
164
            $name .= isset($socketTypeNames[$socket['type']]) ? $socketTypeNames[$socket['type']] : 'Unknown socket';
165
            $tableRows [] = [
166
                $name,
167
                '<info>On</info>',
168
                $socket['handler'],
169
                sprintf('%s:%s', $socket['host'], $socket['port']),
170
            ];
171
        }
172
        $this->table(['Protocol', 'Status', 'Handler', 'Listen At'], $tableRows);
173
    }
174
175
    protected function prepareConfig()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function prepareConfig()
Loading history...
176
    {
177
        $this->loadConfig();
178
179
        $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

179
        $svrConf = /** @scrutinizer ignore-call */ config('laravels');
Loading history...
180
181
        $this->preSet($svrConf);
182
183
        $ret = $this->preCheck($svrConf);
184
        if ($ret !== 0) {
185
            return $ret;
186
        }
187
188
        $laravelConf = [
189
            'root_path'           => $svrConf['laravel_base_path'],
190
            'static_path'         => $svrConf['swoole']['document_root'],
191
            'cleaners'            => array_unique((array)Arr::get($svrConf, 'cleaners', [])),
192
            'register_providers'  => array_unique((array)Arr::get($svrConf, 'register_providers', [])),
193
            'destroy_controllers' => Arr::get($svrConf, 'destroy_controllers', []),
194
            'is_lumen'            => $this->isLumen(),
195
            '_SERVER'             => $_SERVER,
196
            '_ENV'                => $_ENV,
197
        ];
198
199
        $config = ['server' => $svrConf, 'laravel' => $laravelConf];
200
        return file_put_contents($this->getConfigPath(), serialize($config)) > 0 ? 0 : 1;
201
    }
202
203
    protected function getConfigPath()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getConfigPath()
Loading history...
204
    {
205
        return storage_path('laravels.conf');
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

205
        return /** @scrutinizer ignore-call */ storage_path('laravels.conf');
Loading history...
206
    }
207
208
    protected function preSet(array &$svrConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function preSet()
Loading history...
209
    {
210
        if (!isset($svrConf['enable_gzip'])) {
211
            $svrConf['enable_gzip'] = false;
212
        }
213
        if (empty($svrConf['laravel_base_path'])) {
214
            $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

214
            $svrConf['laravel_base_path'] = /** @scrutinizer ignore-call */ base_path();
Loading history...
215
        }
216
        if (empty($svrConf['process_prefix'])) {
217
            $svrConf['process_prefix'] = $svrConf['laravel_base_path'];
218
        }
219
        if ($this->option('ignore')) {
220
            $svrConf['ignore_check_pid'] = true;
221
        } elseif (!isset($svrConf['ignore_check_pid'])) {
222
            $svrConf['ignore_check_pid'] = false;
223
        }
224
        if (empty($svrConf['swoole']['document_root'])) {
225
            $svrConf['swoole']['document_root'] = $svrConf['laravel_base_path'] . '/public';
226
        }
227
        if ($this->option('daemonize')) {
228
            $svrConf['swoole']['daemonize'] = true;
229
        } elseif (!isset($svrConf['swoole']['daemonize'])) {
230
            $svrConf['swoole']['daemonize'] = false;
231
        }
232
        if (empty($svrConf['swoole']['pid_file'])) {
233
            $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

233
            $svrConf['swoole']['pid_file'] = /** @scrutinizer ignore-call */ storage_path('laravels.pid');
Loading history...
234
        }
235
        if (empty($svrConf['timer']['max_wait_time'])) {
236
            $svrConf['timer']['max_wait_time'] = 5;
237
        }
238
239
        // Set X-Version
240
        $xVersion = (string)$this->option('x-version');
241
        if ($xVersion !== '') {
242
            $_SERVER['X_VERSION'] = $_ENV['X_VERSION'] = $xVersion;
243
        }
244
        return 0;
245
    }
246
247
    protected function preCheck(array $svrConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function preCheck()
Loading history...
248
    {
249
        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...
Bug introduced by
swoole_version() of type null is incompatible with the type string expected by parameter $version1 of version_compare(). ( Ignorable by Annotation )

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

249
        if (!empty($svrConf['enable_gzip']) && version_compare(/** @scrutinizer ignore-type */ swoole_version(), '4.1.0', '>=')) {
Loading history...
250
            $this->error('enable_gzip is DEPRECATED since Swoole 4.1.0, set http_compression of Swoole instead, http_compression is disabled by default.');
251
            $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.');
252
            return 1;
253
        }
254
        if (!empty($svrConf['events'])) {
255
            if (empty($svrConf['swoole']['task_worker_num']) || $svrConf['swoole']['task_worker_num'] <= 0) {
256
                $this->error('Asynchronous event listening needs to set task_worker_num > 0');
257
                return 1;
258
            }
259
        }
260
        return 0;
261
    }
262
263
264
    public function publish()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function publish()
Loading history...
265
    {
266
        $basePath = config('laravels.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

266
        $basePath = config('laravels.laravel_base_path') ?: /** @scrutinizer ignore-call */ base_path();
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

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