LaravooleCommand::fire()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Laravoole\Commands;
4
5
use ReflectionClass;
6
7
use Illuminate\Console\Command;
8
use Symfony\Component\Console\Input\InputOption;
9
10
class LaravooleCommand extends Command
11
{
12
    /**
13
     * The name and signature of the console command.
14
     *
15
     * @var string
16
     */
17
    protected $signature = 'laravoole {action : start | stop | reload | reload_task | restart | quit}';
18
19
    /**
20
     * The console command description.
21
     *
22
     * @var string
23
     */
24
    protected $description = 'Laravoole control utilities';
25
26
    /**
27
     * Create a new command instance.
28
     *
29
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
30
     */
31
    public function __construct()
32
    {
33
        parent::__construct();
34
    }
35
36
    /**
37
     * Execute the console command before Laravel < 5.5.
38
     * 
39
     * @return mixed
40
     */
41
    public function fire()
42
    {
43
        $this->handle();
44
    }
45
46
    /**
47
     * Execute the console command.
48
     *
49
     * @return mixed
50
     */
51
    public function handle()
52
    {
53
        switch ($action = $this->argument('action')) {
54
55
            case 'start':
56
                $this->start();
57
                break;
58
            case 'restart':
59
                $pid = $this->sendSignal(SIGTERM);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $pid is correct as $this->sendSignal(SIGTERM) (which targets Laravoole\Commands\LaravooleCommand::sendSignal()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
60
                $time = 0;
61
                while (posix_getpgid($pid) && $time <= 10) {
62
                    usleep(100000);
63
                    $time++;
64
                }
65
                if ($time > 100) {
66
                    echo 'timeout' . PHP_EOL;
67
                    exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method handle() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
68
                }
69
                $this->start();
70
                break;
71
            case 'stop':
72
            case 'quit':
73
            case 'reload':
74
            case 'reload_task':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
75
76
                $map = [
77
                    'stop' => SIGTERM,
78
                    'quit' => SIGQUIT,
79
                    'reload' => SIGUSR1,
80
                    'reload_task' => SIGUSR2,
81
                ];
82
                $this->sendSignal($map[$action]);
83
                break;
84
85
        }
86
    }
87
88
    protected function sendSignal($sig)
89
    {
90
        if ($pid = $this->getPid()) {
91
92
            posix_kill($pid, $sig);
93
        } else {
94
95
            echo "not running!" . PHP_EOL;
96
            exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method sendSignal() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
97
        }
98
    }
99
100
    protected function start()
101
    {
102
        if ($this->getPid()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getPid() of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
103
            echo 'already running' . PHP_EOL;
104
            exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method start() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
105
        }
106
107
        $mode = config('laravoole.base_config.mode');
108
        if (!$mode) {
109
            echo "Laravoole needs Swoole or Workerman." . PHP_EOL .
110
                "You can install Swoole by command:" . PHP_EOL .
111
                " pecl install swoole" . PHP_EOL .
112
                "Or you can install Workerman by command:" . PHP_EOL .
113
                " composer require workerman/workerman" . PHP_EOL;
114
            exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method start() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
115
        }
116
117
        if(!class_exists($wrapper = "Laravoole\\Wrapper\\{$mode}Wrapper")) {
118
            $wrapper = $mode;
119
        }
120
        $ref = new ReflectionClass($wrapper);
121
        $wrapper_file = $ref->getFileName();
122
123
        $handler_config = [];
124
        $params = $wrapper::getParams();
125
        foreach ($params as $paramName => $default) {
126
            if (is_int($paramName)) {
127
                $paramName = $default;
128
                $default = null;
129
            }
130
            $key = $paramName;
131
            $value = config("laravoole.handler_config.{$key}", function () use ($key, $default) {
132
                return env("LARAVOOLE_" . strtoupper($key), $default);
133
            });
134
            if ($value !== null) {
135
                if ((is_array($value) || is_object($value)) && is_callable($value)) {
136
                    $value = $value();
137
                }
138
                $handler_config[$paramName] = $value;
139
            }
140
141
        }
142
143
        $host = config('laravoole.base_config.host');
144
        $port = config('laravoole.base_config.port');
145
        $socket = @stream_socket_server("tcp://{$host}:{$port}");
146
        if(!$socket) {
147
            throw new \Exception("Address {$host}:{$port} already in use", 1);
148
        } else {
149
            fclose($socket);
150
        }
151
152
        $configs = [
153
            'host' => $host,
154
            'port' => $port,
155
            'wrapper_file' => $wrapper_file,
156
            'wrapper' => $wrapper,
157
            'pid_file' => config('laravoole.base_config.pid_file'),
158
            'root_dir' => base_path(),
159
            'callbacks' => config('laravoole.base_config.callbacks'),
160
            // for swoole / workerman
161
            'handler_config' => $handler_config,
162
            // for wrapper, like http / fastcgi / websocket
163
            'wrapper_config' => config('laravoole.wrapper_config'),
164
            'base_config' => config('laravoole.base_config'),
165
        ];
166
167
        $handle = popen(PHP_BINARY . ' ' . __DIR__ . '/../../src/Entry.php', 'w');
168
        fwrite($handle, serialize($configs));
169
        fclose($handle);
170
    }
171
172
    protected function getPid()
173
    {
174
175
        $pid_file = config('laravoole.base_config.pid_file');
176
        if (file_exists($pid_file)) {
177
            $pid = file_get_contents($pid_file);
178
            if (posix_getpgid($pid)) {
179
                return $pid;
180
            } else {
181
                unlink($pid_file);
182
            }
183
        }
184
        return false;
185
    }
186
187
}
188