Completed
Push — master ( bebbc2...ee8156 )
by Biao
03:03
created

LaravelSCommand::showInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
                $this->showInfo();
30
                break;
31
            case 'info':
32
                $this->showInfo();
33
                break;
34
            default:
35
                $this->info(sprintf('Usage: [%s] ./artisan laravels publish|config|info', PHP_BINARY));
36
                if (in_array($action, ['start', 'stop', 'restart', 'reload'], true)) {
37
                    $this->error(sprintf(
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, '
41
                    ));
42
                }
43
                break;
44
        }
45
    }
46
47
    protected function isLumen()
48
    {
49
        return stripos($this->getApplication()->getVersion(), 'Lumen') !== false;
50
    }
51
52
    protected function loadConfig()
53
    {
54
        // Load configuration laravel.php manually for Lumen
55
        $basePath = config('laravels.laravel_base_path') ?: base_path();
56
        if ($this->isLumen() && file_exists($basePath . '/config/laravels.php')) {
57
            $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

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