Passed
Push — master ( 2fc881...676a29 )
by Biao
03:38
created

LaravelSCommand::showComponents()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 19
c 1
b 0
f 0
nc 8
nop 0
dl 0
loc 31
rs 8.8333
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 Hhxsv5\LaravelS\Components\Prometheus\CollectorProcess;
6
use Hhxsv5\LaravelS\Components\Prometheus\TimerProcessMetricsCronJob;
7
use Hhxsv5\LaravelS\Swoole\Timer\PrometheusTimerProcessMetricsCronJob;
0 ignored issues
show
Bug introduced by
The type Hhxsv5\LaravelS\Swoole\T...erProcessMetricsCronJob 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...
8
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...
9
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...
10
11
class LaravelSCommand extends Command
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class LaravelSCommand
Loading history...
12
{
13
    protected $signature = 'laravels {action? : publish|config|info}
14
    {--d|daemonize : Run as a daemon}
15
    {--i|ignore : Ignore checking PID file of Master process}
16
    {--x=|x-version= : The version(branch) of the current project, stored in $_ENV/$_SERVER}';
17
18
    protected $description = 'LaravelS console tool';
19
20
    public function fire()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function fire()
Loading history...
21
    {
22
        $this->handle();
23
    }
24
25
    public function handle()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function handle()
Loading history...
26
    {
27
        $action = (string)$this->argument('action');
28
        switch ($action) {
29
            case 'publish':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
30
                $this->publish();
31
                break;
32
            case 'config':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
33
            case 'info':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
34
                $this->prepareConfig();
35
                $this->showInfo();
36
                break;
37
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
38
                $this->info(sprintf('Usage: [%s] ./artisan laravels publish|config|info', PHP_BINARY));
39
                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...
40
                    $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...
41
                        'The "%s" command has been migrated to "bin/laravels", %ssee https://github.com/hhxsv5/laravel-s#run',
42
                        $action,
43
                        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

43
                        file_exists(/** @scrutinizer ignore-call */ base_path('bin/laravels')) ? '' : 'please run `php artisan laravels publish` first, '
Loading history...
44
                    ));
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...
45
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
46
                break;
47
        }
48
    }
49
50
    protected function isLumen()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function isLumen()
Loading history...
51
    {
52
        return stripos($this->getApplication()->getVersion(), 'Lumen') !== false;
53
    }
54
55
    protected function loadConfig()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function loadConfig()
Loading history...
56
    {
57
        // Load configuration laravel.php manually for Lumen
58
        $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

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

58
        $basePath = /** @scrutinizer ignore-call */ config('laravels.laravel_base_path') ?: base_path();
Loading history...
59
        if ($this->isLumen() && file_exists($basePath . '/config/laravels.php')) {
60
            $this->getLaravel()->configure('laravels');
61
        }
62
    }
63
64
    protected function showInfo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showInfo()
Loading history...
65
    {
66
        $this->showLogo();
67
        $this->showComponents();
68
        $this->showProtocols();
69
        $this->comment('>>> Feedback: <options=underscore>https://github.com/hhxsv5/laravel-s</>');
70
    }
71
72
    protected function showLogo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showLogo()
Loading history...
73
    {
74
        static $logo = <<<EOS
75
 _                               _  _____ 
76
| |                             | |/ ____|
77
| |     __ _ _ __ __ ___   _____| | (___  
78
| |    / _` | '__/ _` \ \ / / _ \ |\___ \ 
79
| |___| (_| | | | (_| |\ V /  __/ |____) |
80
|______\__,_|_|  \__,_| \_/ \___|_|_____/ 
81
                                           
82
EOS;
83
        $this->info($logo);
84
        $this->info('Speed up your Laravel/Lumen');
85
    }
86
87
    protected function showComponents()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function showComponents()
Loading history...
88
    {
89
        $this->comment('>>> Components');
90
        $laravelSVersion = '-';
91
        $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

91
        $lockFile = /** @scrutinizer ignore-call */ base_path('composer.lock');
Loading history...
92
        $cfg = file_exists($lockFile) ? json_decode(file_get_contents($lockFile), true) : [];
93
        if (isset($cfg['packages'])) {
94
            $packages = array_merge($cfg['packages'], Arr::get($cfg, 'packages-dev', []));
95
            foreach ($packages as $package) {
96
                if (isset($package['name']) && $package['name'] === 'hhxsv5/laravel-s') {
97
                    $laravelSVersion = ltrim($package['version'], 'vV');
98
                    break;
99
                }
100
            }
101
        }
102
        $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...
103
            [
104
                'PHP',
105
                PHP_VERSION,
106
            ],
107
            [
108
                extension_loaded('openswoole') ? 'Open Swoole' : 'Swoole',
109
                SWOOLE_VERSION,
110
            ],
111
            [
112
                'LaravelS',
113
                $laravelSVersion,
114
            ],
115
            [
116
                $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

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

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

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

213
        return /** @scrutinizer ignore-call */ storage_path('laravels.conf');
Loading history...
214
    }
215
216
    protected function preSet(array &$svrConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function preSet()
Loading history...
217
    {
218
        if (!isset($svrConf['enable_gzip'])) {
219
            $svrConf['enable_gzip'] = false;
220
        }
221
        if (empty($svrConf['laravel_base_path'])) {
222
            $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

222
            $svrConf['laravel_base_path'] = /** @scrutinizer ignore-call */ base_path();
Loading history...
223
        }
224
        if (empty($svrConf['process_prefix'])) {
225
            $svrConf['process_prefix'] = $svrConf['laravel_base_path'];
226
        }
227
        if ($this->option('ignore')) {
228
            $svrConf['ignore_check_pid'] = true;
229
        } elseif (!isset($svrConf['ignore_check_pid'])) {
230
            $svrConf['ignore_check_pid'] = false;
231
        }
232
        if (empty($svrConf['swoole']['document_root'])) {
233
            $svrConf['swoole']['document_root'] = $svrConf['laravel_base_path'] . '/public';
234
        }
235
        if ($this->option('daemonize')) {
236
            $svrConf['swoole']['daemonize'] = true;
237
        } elseif (!isset($svrConf['swoole']['daemonize'])) {
238
            $svrConf['swoole']['daemonize'] = false;
239
        }
240
        if (empty($svrConf['swoole']['pid_file'])) {
241
            $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

241
            $svrConf['swoole']['pid_file'] = /** @scrutinizer ignore-call */ storage_path('laravels.pid');
Loading history...
242
        }
243
        if (empty($svrConf['timer']['max_wait_time'])) {
244
            $svrConf['timer']['max_wait_time'] = 5;
245
        }
246
247
        // Configure PrometheusTimerProcessMetricsCronJob automatically
248
        if (isset($svrConf['processes']) && !empty($svrConf['timer']['enable'])) {
249
            foreach ($svrConf['processes'] as $process) {
250
                if ($process['class'] === CollectorProcess::class && (!isset($process['enable']) || $process['enable'])) {
251
                    $svrConf['timer']['jobs'][] = TimerProcessMetricsCronJob::class;
252
                    break;
253
                }
254
            }
255
        }
256
257
        // Set X-Version
258
        $xVersion = (string)$this->option('x-version');
259
        if ($xVersion !== '') {
260
            $_SERVER['X_VERSION'] = $_ENV['X_VERSION'] = $xVersion;
261
        }
262
        return 0;
263
    }
264
265
    protected function preCheck(array $svrConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function preCheck()
Loading history...
266
    {
267
        if (!empty($svrConf['enable_gzip']) && version_compare(SWOOLE_VERSION, '4.1.0', '>=')) {
268
            $this->error('enable_gzip is DEPRECATED since Swoole 4.1.0, set http_compression of Swoole instead, http_compression is disabled by default.');
269
            $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.');
270
            return 1;
271
        }
272
        if (!empty($svrConf['events'])) {
273
            if (empty($svrConf['swoole']['task_worker_num']) || $svrConf['swoole']['task_worker_num'] <= 0) {
274
                $this->error('Asynchronous event listening needs to set task_worker_num > 0');
275
                return 1;
276
            }
277
        }
278
        return 0;
279
    }
280
281
282
    public function publish()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function publish()
Loading history...
283
    {
284
        $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

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

284
        $basePath = config('laravels.laravel_base_path') ?: /** @scrutinizer ignore-call */ base_path();
Loading history...
285
        $configPath = $basePath . '/config/laravels.php';
286
        $todoList = [
287
            [
288
                'from' => realpath(__DIR__ . '/../../config/laravels.php'),
289
                'to'   => $configPath,
290
                'mode' => 0644,
291
            ],
292
            [
293
                'from' => realpath(__DIR__ . '/../../bin/laravels'),
294
                'to'   => $basePath . '/bin/laravels',
295
                'mode' => 0755,
296
                'link' => true,
297
            ],
298
            [
299
                'from' => realpath(__DIR__ . '/../../bin/fswatch'),
300
                'to'   => $basePath . '/bin/fswatch',
301
                'mode' => 0755,
302
                'link' => true,
303
            ],
304
            [
305
                'from' => realpath(__DIR__ . '/../../bin/inotify'),
306
                'to'   => $basePath . '/bin/inotify',
307
                'mode' => 0755,
308
                'link' => true,
309
            ],
310
        ];
311
        if (file_exists($configPath)) {
312
            $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...
313
                ['Y', 'N'],
314
                'N'
315
            );
316
            if (!$choice || strtoupper($choice) !== 'Y') {
317
                array_shift($todoList);
318
            }
319
        }
320
321
        foreach ($todoList as $todo) {
322
            $toDir = dirname($todo['to']);
323
            if (!is_dir($toDir) && !mkdir($toDir, 0755, true) && !is_dir($toDir)) {
324
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $toDir));
325
            }
326
            if (file_exists($todo['to'])) {
327
                unlink($todo['to']);
328
            }
329
            $operation = 'Copied';
330
            if (empty($todo['link'])) {
331
                copy($todo['from'], $todo['to']);
332
            } elseif (@link($todo['from'], $todo['to'])) {
333
                $operation = 'Linked';
334
            } else {
335
                copy($todo['from'], $todo['to']);
336
            }
337
            chmod($todo['to'], $todo['mode']);
338
            $this->line("<info>{$operation} file</info> <comment>[{$todo['from']}]</comment> <info>To</info> <comment>[{$todo['to']}]</comment>");
339
        }
340
        return 0;
341
    }
342
}
343