Completed
Push — master ( 10f5da...bebbc2 )
by Biao
03:04
created

LaravelSCommand::preSet()   C

Complexity

Conditions 10
Paths 288

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 19
nc 288
nop 1
dl 0
loc 28
rs 5.7333
c 0
b 0
f 0

How to fix   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
3
namespace Hhxsv5\LaravelS\Illuminate;
4
5
use Illuminate\Console\Command;
6
7
class LaravelSCommand extends Command
8
{
9
    protected $signature = 'laravels {action? : publish|config|info}
10
    {--d|daemonize : Whether run as a daemon for "start & restart"}
11
    {--i|ignore : Whether ignore checking process pid for "start & restart"}';
12
13
    protected $description = 'LaravelS console tool';
14
15
    public function fire()
16
    {
17
        $this->handle();
18
    }
19
20
    public function handle()
21
    {
22
        $action = (string)$this->argument('action');
23
        switch ($action) {
24
            case 'publish':
25
                $this->publish();
26
                break;
27
            case 'config':
28
                $this->prepareConfig();
29
                break;
30
            case 'info':
31
                $this->showLogo();
32
                $this->showComponents();
33
                $this->showDashboard();
34
                break;
35
            default:
36
                $this->info(sprintf('Usage: [%s] ./artisan laravels publish|config|info', PHP_BINARY));
37
                if (in_array($action, ['start', 'stop', 'restart', 'reload'], true)) {
38
                    $this->error(sprintf(
39
                        'The "%s" command has been migrated to "bin/laravels", %ssee https://github.com/hhxsv5/laravel-s#run',
40
                        $action,
41
                        file_exists(base_path('bin/laravels')) ? '' : 'please run `php artisan laravels publish` first, '
42
                    ));
43
                }
44
                break;
45
        }
46
    }
47
48
    protected function isLumen()
49
    {
50
        return stripos($this->getApplication()->getVersion(), 'Lumen') !== false;
51
    }
52
53
    protected function loadConfig()
54
    {
55
        // Load configuration laravel.php manually for Lumen
56
        $basePath = config('laravels.laravel_base_path') ?: base_path();
57
        if ($this->isLumen() && file_exists($basePath . '/config/laravels.php')) {
58
            $this->getLaravel()->configure('laravels');
0 ignored issues
show
Bug introduced by
The method configure() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

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

58
            $this->getLaravel()->/** @scrutinizer ignore-call */ configure('laravels');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
59
        }
60
    }
61
62
    protected function showLogo()
63
    {
64
        static $logo = <<<EOS
65
 _                               _  _____ 
66
| |                             | |/ ____|
67
| |     __ _ _ __ __ ___   _____| | (___  
68
| |    / _` | '__/ _` \ \ / / _ \ |\___ \ 
69
| |___| (_| | | | (_| |\ V /  __/ |____) |
70
|______\__,_|_|  \__,_| \_/ \___|_|_____/ 
71
                                           
72
EOS;
73
        $this->info($logo);
74
        $this->info('Speed up your Laravel/Lumen');
75
    }
76
77
    protected function showComponents()
78
    {
79
        $this->comment('>>> Components');
80
        $laravelSVersion = '-';
81
        $cfg = (array)json_decode(file_get_contents(base_path('composer.lock')), true);
82
        if (isset($cfg['packages'])) {
83
            $packages = array_merge($cfg['packages'], array_get($cfg, 'packages-dev', []));
84
            foreach ($packages as $package) {
85
                if (isset($package['name']) && $package['name'] === 'hhxsv5/laravel-s') {
86
                    $laravelSVersion = ltrim($package['version'], 'vV');
87
                    break;
88
                }
89
            }
90
        }
91
        $this->table(['Component', 'Version'], [
92
            [
93
                'PHP',
94
                phpversion(),
95
            ],
96
            [
97
                'Swoole',
98
                swoole_version(),
99
            ],
100
            [
101
                'LaravelS',
102
                $laravelSVersion,
103
            ],
104
            [
105
                $this->getApplication()->getName() . ' [<info>' . env('APP_ENV') . '</info>]',
106
                $this->getApplication()->getVersion(),
107
            ],
108
        ]);
109
    }
110
111
    protected function showDashboard()
112
    {
113
        $this->comment('>>> Dashboard');
114
115
        $config = (array)json_decode(file_get_contents(base_path('storage/laravels.json')), true);
116
        if (in_array($config['server']['socket_type'], [SWOOLE_SOCK_UNIX_DGRAM, SWOOLE_SOCK_UNIX_STREAM])) {
117
            $listenAt = $config['server']['listen_ip'];
118
        } else {
119
            $listenAt = sprintf('%s:%s', $config['server']['listen_ip'], $config['server']['listen_port']);
120
        }
121
122
        $tableRows = [
123
            [
124
                'Main HTTP',
125
                '<info>On</info>',
126
                empty($config['laravel']['is_lumen']) ? 'Laravel' : 'Lumen',
127
                $listenAt,
128
            ],
129
            [
130
                'Main WebSocket',
131
                empty($config['server']['websocket']['enable']) ? 'Off' : '<info>On</info>',
132
                empty($config['server']['websocket']['handler']) ? '-' : $config['server']['websocket']['handler'],
133
                $listenAt,
134
            ],
135
        ];
136
        $socketTypeNames = [
137
            SWOOLE_SOCK_TCP         => 'TCP IPV4 Socket',
138
            SWOOLE_SOCK_TCP6        => 'TCP IPV6 Socket',
139
            SWOOLE_SOCK_UDP         => 'UDP IPV4 Socket',
140
            SWOOLE_SOCK_UDP6        => 'TCP IPV6 Socket',
141
            SWOOLE_SOCK_UNIX_DGRAM  => 'Unix Socket Dgram',
142
            SWOOLE_SOCK_UNIX_STREAM => 'Unix Socket Stream',
143
        ];
144
        foreach ($config['server']['sockets'] as $key => $socket) {
145
            $name = isset($socketTypeNames[$socket['type']]) ? $socketTypeNames[$socket['type']] : 'Unknown socket';
146
            $name .= ' #' . ($key + 1);
147
            $tableRows [] = [
148
                $name,
149
                '<info>On</info>',
150
                $socket['handler'],
151
                sprintf('%s:%s', $socket['host'], $socket['port']),
152
            ];
153
        }
154
        $this->table(['Protocol', 'Status', 'Handler', 'Listen At'], $tableRows);
155
156
        $this->comment('>>> Feedback: <options=underscore>https://github.com/hhxsv5/laravel-s</>');
157
    }
158
159
    protected function prepareConfig()
160
    {
161
        $this->loadConfig();
162
163
        $svrConf = config('laravels');
164
165
        $this->preSet($svrConf);
166
167
        $ret = $this->preCheck($svrConf);
168
        if ($ret !== 0) {
169
            return $ret;
170
        }
171
172
        $laravelConf = [
173
            'root_path'          => $svrConf['laravel_base_path'],
174
            'static_path'        => $svrConf['swoole']['document_root'],
175
            'register_providers' => array_unique((array)array_get($svrConf, 'register_providers', [])),
176
            'is_lumen'           => $this->isLumen(),
177
            '_SERVER'            => $_SERVER,
178
            '_ENV'               => $_ENV,
179
        ];
180
181
        $config = ['server' => $svrConf, 'laravel' => $laravelConf];
182
        $jsonConfig = json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
183
        return file_put_contents(base_path('storage/laravels.json'), $jsonConfig) > 0 ? 0 : 1;
184
    }
185
186
    protected function preSet(array &$svrConf)
187
    {
188
        if (!isset($svrConf['enable_gzip'])) {
189
            $svrConf['enable_gzip'] = false;
190
        }
191
        if (empty($svrConf['laravel_base_path'])) {
192
            $svrConf['laravel_base_path'] = base_path();
193
        }
194
        if (empty($svrConf['process_prefix'])) {
195
            $svrConf['process_prefix'] = $svrConf['laravel_base_path'];
196
        }
197
        if ($this->option('ignore')) {
198
            $svrConf['ignore_check_pid'] = true;
199
        } elseif (!isset($svrConf['ignore_check_pid'])) {
200
            $svrConf['ignore_check_pid'] = false;
201
        }
202
        if (empty($svrConf['swoole']['document_root'])) {
203
            $svrConf['swoole']['document_root'] = $svrConf['laravel_base_path'] . '/public';
204
        }
205
        if ($this->option('daemonize')) {
206
            $svrConf['swoole']['daemonize'] = true;
207
        } elseif (!isset($svrConf['swoole']['daemonize'])) {
208
            $svrConf['swoole']['daemonize'] = false;
209
        }
210
        if (empty($svrConf['swoole']['pid_file'])) {
211
            $svrConf['swoole']['pid_file'] = storage_path('laravels.pid');
212
        }
213
        return 0;
214
    }
215
216
    protected function preCheck(array $svrConf)
217
    {
218
        if (!empty($svrConf['enable_gzip']) && version_compare(swoole_version(), '4.1.0', '>=')) {
219
            $this->error('enable_gzip is DEPRECATED since Swoole 4.1.0, set http_compression of Swoole instead, http_compression is disabled by default.');
220
            $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.');
221
            return 1;
222
        }
223
        if (!empty($svrConf['events'])) {
224
            if (empty($svrConf['swoole']['task_worker_num']) || $svrConf['swoole']['task_worker_num'] <= 0) {
225
                $this->error('Asynchronous event listening needs to set task_worker_num > 0');
226
                return 1;
227
            }
228
        }
229
        return 0;
230
    }
231
232
233
    public function publish()
234
    {
235
        $basePath = config('laravels.laravel_base_path') ?: base_path();
236
        $configPath = $basePath . '/config/laravels.php';
237
        $todoList = [
238
            [
239
                'from' => realpath(__DIR__ . '/../../config/laravels.php'),
240
                'to'   => $configPath,
241
                'mode' => 0644,
242
            ],
243
            [
244
                'from' => realpath(__DIR__ . '/../../bin/laravels'),
245
                'to'   => $basePath . '/bin/laravels',
246
                'mode' => 0755,
247
                'link' => true,
248
            ],
249
            [
250
                'from' => realpath(__DIR__ . '/../../bin/fswatch'),
251
                'to'   => $basePath . '/bin/fswatch',
252
                'mode' => 0755,
253
                'link' => true,
254
            ],
255
        ];
256
        if (file_exists($configPath)) {
257
            $choice = $this->anticipate($configPath . ' already exists, do you want to override it ? Y/N',
258
                ['Y', 'N'],
259
                'N'
260
            );
261
            if (!$choice || strtoupper($choice) !== 'Y') {
262
                array_shift($todoList);
263
            }
264
        }
265
266
        foreach ($todoList as $todo) {
267
            $toDir = dirname($todo['to']);
268
            if (!is_dir($toDir)) {
269
                mkdir($toDir, 0755, true);
270
            }
271
            if (file_exists($todo['to'])) {
272
                unlink($todo['to']);
273
            }
274
            $operation = 'Copied';
275
            if (empty($todo['link'])) {
276
                copy($todo['from'], $todo['to']);
277
            } else {
278
                if (@link($todo['from'], $todo['to'])) {
279
                    $operation = 'Linked';
280
                } else {
281
                    copy($todo['from'], $todo['to']);
282
                }
283
284
            }
285
            chmod($todo['to'], $todo['mode']);
286
            $this->line("<info>{$operation} file</info> <comment>[{$todo['from']}]</comment> <info>To</info> <comment>[{$todo['to']}]</comment>");
287
        }
288
        return 0;
289
    }
290
}
291