Passed
Push — master ( 0c431b...97c469 )
by Biao
06:29
created

LaravelSCommand   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 206
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 123
dl 0
loc 206
rs 8.96
c 0
b 0
f 0
wmc 43

9 Methods

Rating   Name   Duplication   Size   Complexity  
A isLumen() 0 3 1
A fire() 0 3 1
A handle() 0 16 4
A showInfo() 0 39 5
A prepareConfig() 0 26 2
A loadConfig() 0 6 4
B publish() 0 42 10
C preSet() 0 28 10
A preCheck() 0 14 6

How to fix   Complexity   

Complex Class

Complex classes like LaravelSCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LaravelSCommand, and based on these observations, apply Extract Interface, too.

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->showInfo();
32
                break;
33
            default:
34
                $this->info(sprintf('Usage: [%s] ./artisan laravels publish|config|info', PHP_BINARY));
35
                break;
36
        }
37
    }
38
39
    protected function isLumen()
40
    {
41
        return stripos($this->getApplication()->getVersion(), 'Lumen') !== false;
42
    }
43
44
    protected function loadConfig()
45
    {
46
        // Load configuration laravel.php manually for Lumen
47
        $basePath = config('laravels.laravel_base_path') ?: base_path();
48
        if ($this->isLumen() && file_exists($basePath . '/config/laravels.php')) {
49
            $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

49
            $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...
50
        }
51
    }
52
53
    protected function showInfo()
54
    {
55
        static $logo = <<<EOS
56
 _                               _  _____ 
57
| |                             | |/ ____|
58
| |     __ _ _ __ __ ___   _____| | (___  
59
| |    / _` | '__/ _` \ \ / / _ \ |\___ \ 
60
| |___| (_| | | | (_| |\ V /  __/ |____) |
61
|______\__,_|_|  \__,_| \_/ \___|_|_____/ 
62
                                           
63
EOS;
64
        $this->info($logo);
65
        $this->comment('Speed up your Laravel/Lumen');
66
        $laravelSVersion = '-';
67
        $cfg = json_decode(file_get_contents(base_path('composer.lock')), true);
68
        if (isset($cfg['packages'])) {
69
            foreach ($cfg['packages'] as $pkg) {
70
                if (isset($pkg['name']) && $pkg['name'] === 'hhxsv5/laravel-s') {
71
                    $laravelSVersion = ltrim($pkg['version'], 'vV');
72
                    break;
73
                }
74
            }
75
        }
76
        $this->table(['Component', 'Version'], [
77
            [
78
                'Component' => 'PHP',
79
                'Version'   => phpversion(),
80
            ],
81
            [
82
                'Component' => 'Swoole',
83
                'Version'   => swoole_version(),
84
            ],
85
            [
86
                'Component' => 'LaravelS',
87
                'Version'   => $laravelSVersion,
88
            ],
89
            [
90
                'Component' => $this->getApplication()->getName(),
91
                'Version'   => $this->getApplication()->getVersion(),
92
            ],
93
        ]);
94
    }
95
96
    protected function prepareConfig()
97
    {
98
        $this->loadConfig();
99
100
        $svrConf = config('laravels');
101
102
        $this->preSet($svrConf);
103
104
        $ret = $this->preCheck($svrConf);
105
        if ($ret !== 0) {
106
            return $ret;
107
        }
108
109
        $laravelConf = [
110
            'root_path'          => $svrConf['laravel_base_path'],
111
            'static_path'        => $svrConf['swoole']['document_root'],
112
            'register_providers' => array_unique((array)array_get($svrConf, 'register_providers', [])),
113
            'is_lumen'           => $this->isLumen(),
114
            '_SERVER'            => $_SERVER,
115
            '_ENV'               => $_ENV,
116
        ];
117
118
        $config = ['server' => $svrConf, 'laravel' => $laravelConf];
119
        $config = json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
120
        file_put_contents(base_path('storage/laravels.json'), $config);
121
        return 0;
122
    }
123
124
    protected function preSet(array &$svrConf)
125
    {
126
        if (!isset($svrConf['enable_gzip'])) {
127
            $svrConf['enable_gzip'] = false;
128
        }
129
        if (empty($svrConf['laravel_base_path'])) {
130
            $svrConf['laravel_base_path'] = base_path();
131
        }
132
        if (empty($svrConf['process_prefix'])) {
133
            $svrConf['process_prefix'] = $svrConf['laravel_base_path'];
134
        }
135
        if ($this->option('ignore')) {
136
            $svrConf['ignore_check_pid'] = true;
137
        } elseif (!isset($svrConf['ignore_check_pid'])) {
138
            $svrConf['ignore_check_pid'] = false;
139
        }
140
        if (empty($svrConf['swoole']['document_root'])) {
141
            $svrConf['swoole']['document_root'] = $svrConf['laravel_base_path'] . '/public';
142
        }
143
        if ($this->option('daemonize')) {
144
            $svrConf['swoole']['daemonize'] = true;
145
        } elseif (!isset($svrConf['swoole']['daemonize'])) {
146
            $svrConf['swoole']['daemonize'] = false;
147
        }
148
        if (empty($svrConf['swoole']['pid_file'])) {
149
            $svrConf['swoole']['pid_file'] = storage_path('laravels.pid');
150
        }
151
        return 0;
152
    }
153
154
    protected function preCheck(array $svrConf)
155
    {
156
        if (!empty($svrConf['enable_gzip']) && version_compare(swoole_version(), '4.1.0', '>=')) {
157
            $this->error('enable_gzip is DEPRECATED since Swoole 4.1.0, set http_compression of Swoole instead, http_compression is disabled by default.');
158
            $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.');
159
            return 1;
160
        }
161
        if (!empty($svrConf['events'])) {
162
            if (empty($svrConf['swoole']['task_worker_num']) || $svrConf['swoole']['task_worker_num'] <= 0) {
163
                $this->error('Asynchronous event listening needs to set task_worker_num > 0');
164
                return 1;
165
            }
166
        }
167
        return 0;
168
    }
169
170
171
    public function publish()
172
    {
173
        $basePath = config('laravels.laravel_base_path') ?: base_path();
174
        $configPath = $basePath . '/config/laravels.php';
175
        $todoList = [
176
            ['from' => realpath(__DIR__ . '/../../config/laravels.php'), 'to' => $configPath, 'mode' => 0644],
177
            ['from' => realpath(__DIR__ . '/../../bin/laravels'), 'to' => $basePath . '/bin/laravels', 'mode' => 0755, 'link' => true],
178
            ['from' => realpath(__DIR__ . '/../../bin/fswatch'), 'to' => $basePath . '/bin/fswatch', 'mode' => 0755, 'link' => true],
179
        ];
180
        if (file_exists($configPath)) {
181
            $choice = $this->anticipate($configPath . ' already exists, do you want to override it ? Y/N',
182
                ['Y', 'N'],
183
                'N'
184
            );
185
            if (!$choice || strtoupper($choice) !== 'Y') {
186
                array_shift($todoList);
187
            }
188
        }
189
190
        foreach ($todoList as $todo) {
191
            $toDir = dirname($todo['to']);
192
            if (!is_dir($toDir)) {
193
                mkdir($toDir, 0755, true);
194
            }
195
            if (file_exists($todo['to'])) {
196
                unlink($todo['to']);
197
            }
198
            $operation = 'Copied';
199
            if (empty($todo['link'])) {
200
                copy($todo['from'], $todo['to']);
201
            } else {
202
                if (@link($todo['from'], $todo['to'])) {
203
                    $operation = 'Linked';
204
                } else {
205
                    copy($todo['from'], $todo['to']);
206
                }
207
208
            }
209
            chmod($todo['to'], $todo['mode']);
210
            $this->line("<info>{$operation} file</info> <comment>[{$todo['from']}]</comment> <info>To</info> <comment>[{$todo['to']}]</comment>");
211
        }
212
        return 0;
213
    }
214
}
215