diff --git a/src/Connection/AsyncTcpConnection.php b/src/Connection/AsyncTcpConnection.php index 29a7e602d..041f94d48 100644 --- a/src/Connection/AsyncTcpConnection.php +++ b/src/Connection/AsyncTcpConnection.php @@ -53,7 +53,7 @@ class AsyncTcpConnection extends TcpConnection /** * PHP built-in protocols. * - * @var array + * @var array */ public const BUILD_IN_TRANSPORTS = [ 'tcp' => 'tcp', @@ -230,7 +230,7 @@ public function reconnect(int $after = 0): void Timer::del($this->reconnectTimer); } if ($after > 0) { - $this->reconnectTimer = Timer::add($after, [$this, 'connect'], null, false); + $this->reconnectTimer = Timer::add($after, $this->connect(...), null, false); return; } $this->connect(); @@ -302,10 +302,10 @@ public function connect(): void return; } // Add socket to global event loop waiting connection is successfully established or failed. - $this->eventLoop->onWritable($this->socket, [$this, 'checkConnection']); + $this->eventLoop->onWritable($this->socket, $this->checkConnection(...)); // For windows. if (DIRECTORY_SEPARATOR === '\\' && method_exists($this->eventLoop, 'onExcept')) { - $this->eventLoop->onExcept($this->socket, [$this, 'checkConnection']); + $this->eventLoop->onExcept($this->socket, $this->checkConnection(...)); } } @@ -402,11 +402,11 @@ public function checkConnection(): void } else { // There are some data waiting to send. if ($this->sendBuffer) { - $this->eventLoop->onWritable($this->socket, [$this, 'baseWrite']); + $this->eventLoop->onWritable($this->socket, $this->baseWrite(...)); } } // Register a listener waiting read event. - $this->eventLoop->onReadable($this->socket, [$this, 'baseRead']); + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); $this->status = self::STATUS_ESTABLISHED; $this->remoteAddress = $address; @@ -422,13 +422,12 @@ public function checkConnection(): void // Try to emit protocol::onConnect if ($this->protocol && method_exists($this->protocol, 'onConnect')) { try { - [$this->protocol, 'onConnect']($this); + $this->protocol::onConnect($this); } catch (Throwable $e) { $this->error($e); } } } else { - // Connection failed. $this->emitError(static::CONNECT_FAIL, 'connect ' . $this->remoteAddress . ' fail after ' . round(microtime(true) - $this->connectStartTime, 4) . ' seconds'); if ($this->status === self::STATUS_CLOSING) { @@ -438,6 +437,5 @@ public function checkConnection(): void $this->onConnect = null; } } - } } diff --git a/src/Connection/AsyncUdpConnection.php b/src/Connection/AsyncUdpConnection.php index a5e5972df..dfed54fd3 100644 --- a/src/Connection/AsyncUdpConnection.php +++ b/src/Connection/AsyncUdpConnection.php @@ -202,7 +202,7 @@ public function connect(): void stream_set_blocking($this->socket, false); if ($this->onMessage) { - $this->eventLoop->onReadable($this->socket, [$this, 'baseRead']); + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); } $this->connected = true; // Try to emit onConnect callback. @@ -214,5 +214,4 @@ public function connect(): void } } } - } diff --git a/src/Connection/ConnectionInterface.php b/src/Connection/ConnectionInterface.php index ca1fc44cb..0983cc245 100644 --- a/src/Connection/ConnectionInterface.php +++ b/src/Connection/ConnectionInterface.php @@ -58,7 +58,7 @@ abstract class ConnectionInterface * Application layer protocol. * The format is like this Workerman\\Protocols\\Http. * - * @var ?string + * @var ?class-string */ public ?string $protocol = null; @@ -188,5 +188,4 @@ public function error(Throwable $exception): void throw $exception; } } - } diff --git a/src/Connection/TcpConnection.php b/src/Connection/TcpConnection.php index 019f3d231..fe594f7ee 100644 --- a/src/Connection/TcpConnection.php +++ b/src/Connection/TcpConnection.php @@ -349,7 +349,7 @@ public function __construct(EventInterface $eventLoop, $socket, string $remoteAd stream_set_read_buffer($this->socket, 0); } $this->eventLoop = $eventLoop; - $this->eventLoop->onReadable($this->socket, [$this, 'baseRead']); + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); $this->maxSendBufferSize = self::$defaultMaxSendBufferSize; $this->maxPackageSize = self::$defaultMaxPackageSize; $this->remoteAddress = $remoteAddress; @@ -415,7 +415,7 @@ public function send(mixed $sendBuffer, bool $raw = false) // Attempt to send data directly. if ($this->sendBuffer === '') { if ($this->transport === 'ssl') { - $this->eventLoop->onWritable($this->socket, [$this, 'baseWrite']); + $this->eventLoop->onWritable($this->socket, $this->baseWrite(...)); $this->sendBuffer = $sendBuffer; $this->checkBufferWillFull(); return; @@ -451,7 +451,7 @@ public function send(mixed $sendBuffer, bool $raw = false) } $this->sendBuffer = $sendBuffer; } - $this->eventLoop->onWritable($this->socket, [$this, 'baseWrite']); + $this->eventLoop->onWritable($this->socket, $this->baseWrite(...)); // Check if send buffer will be full. $this->checkBufferWillFull(); return; @@ -587,7 +587,7 @@ public function pauseRecv(): void public function resumeRecv(): void { if ($this->isPaused === true) { - $this->eventLoop->onReadable($this->socket, [$this, 'baseRead']); + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); $this->isPaused = false; $this->baseRead($this->socket, false); } @@ -610,7 +610,7 @@ public function baseRead($socket, bool $checkEof = true): void if ($this->doSslHandshake($socket)) { $this->sslHandshakeCompleted = true; if ($this->sendBuffer) { - $this->eventLoop->onWritable($socket, [$this, 'baseWrite']); + $this->eventLoop->onWritable($socket, $this->baseWrite(...)); } } else { return; @@ -621,6 +621,7 @@ public function baseRead($socket, bool $checkEof = true): void try { $buffer = @fread($socket, self::READ_BUFFER_SIZE); } catch (Throwable) { + // do nothing } // Check connection closed. @@ -1018,7 +1019,7 @@ public function destroy(): void // Try to emit protocol::onClose if ($this->protocol && method_exists($this->protocol, 'onClose')) { try { - ([$this->protocol, 'onClose'])($this); + $this->protocol::onClose($this); } catch (Throwable $e) { $this->error($e); } diff --git a/src/Events/Select.php b/src/Events/Select.php index 5e33b5067..4998f32ba 100644 --- a/src/Events/Select.php +++ b/src/Events/Select.php @@ -469,5 +469,4 @@ public function error(Throwable $e): void } ($this->errorHandler)($e); } - } diff --git a/src/Events/Swoole.php b/src/Events/Swoole.php index 1e2c9eea0..64e6d1e3e 100644 --- a/src/Events/Swoole.php +++ b/src/Events/Swoole.php @@ -263,5 +263,4 @@ public function error(Throwable $e): void } ($this->errorHandler)($e); } - } diff --git a/src/Protocols/Http.php b/src/Protocols/Http.php index bd76a9393..62a42482c 100644 --- a/src/Protocols/Http.php +++ b/src/Protocols/Http.php @@ -123,9 +123,8 @@ public static function input(string $buffer, TcpConnection $connection): int } $header = substr($buffer, 0, $crlfPos); - $hostHeaderPosition = stripos($header, "\r\nHost: "); - if (false === $hostHeaderPosition && $firstLine[2] === "HTTP/1.1") { + if (!str_contains($header, "\r\nHost: ") && $firstLine[2] === "HTTP/1.1") { $connection->close("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n", true); return 0; } @@ -138,7 +137,7 @@ public static function input(string $buffer, TcpConnection $connection): int $hasContentLength = true; } else { $hasContentLength = false; - if (false !== stripos($header, "\r\nTransfer-Encoding:")) { + if (str_contains($header, "\r\nTransfer-Encoding:")) { $connection->close("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n", true); return 0; } diff --git a/src/Protocols/Http/Response.php b/src/Protocols/Http/Response.php index 9ec9ec75c..7a4c9e2f4 100644 --- a/src/Protocols/Http/Response.php +++ b/src/Protocols/Http/Response.php @@ -90,7 +90,7 @@ class Response implements Stringable /** * Phrases. * - * @var array + * @var array * * @link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes */ diff --git a/src/Protocols/Http/Session/RedisClusterSessionHandler.php b/src/Protocols/Http/Session/RedisClusterSessionHandler.php index 68d371638..685dc0334 100644 --- a/src/Protocols/Http/Session/RedisClusterSessionHandler.php +++ b/src/Protocols/Http/Session/RedisClusterSessionHandler.php @@ -52,5 +52,4 @@ public function read(string $sessionId): string { return $this->redis->get($sessionId); } - } diff --git a/src/Protocols/Websocket.php b/src/Protocols/Websocket.php index 5b63b6d02..00f5a3776 100644 --- a/src/Protocols/Websocket.php +++ b/src/Protocols/Websocket.php @@ -432,5 +432,4 @@ public static function dealHandshake(string $buffer, TcpConnection $connection): "HTTP/1.0 200 OK\r\nServer: workerman\r\n\r\n

WebSocket


workerman
", true); return 0; } - } diff --git a/src/Timer.php b/src/Timer.php index c4053ed7d..3398b40e2 100644 --- a/src/Timer.php +++ b/src/Timer.php @@ -85,7 +85,7 @@ public static function init(EventInterface $event = null): void return; } if (function_exists('pcntl_signal')) { - pcntl_signal(SIGALRM, ['\Workerman\Timer', 'signalHandle'], false); + pcntl_signal(SIGALRM, self::signalHandle(...), false); } } diff --git a/src/Worker.php b/src/Worker.php index 120ffe86e..d8d9be51a 100644 --- a/src/Worker.php +++ b/src/Worker.php @@ -328,6 +328,7 @@ class Worker /** * Command + * * @var string */ public static string $command = ''; @@ -356,6 +357,7 @@ class Worker /** * parse from socketName avoid parse again in master or worker * LocalSocket The format is like tcp://0.0.0.0:8080 + * * @var ?string */ protected ?string $localSocket = null; @@ -495,7 +497,7 @@ class Worker /** * PHP built-in protocols. * - * @var array + * @var array */ public const BUILD_IN_TRANSPORTS = [ 'tcp' => 'tcp', @@ -507,7 +509,7 @@ class Worker /** * PHP built-in error types. * - * @var array + * @var array */ public const ERROR_TYPE = [ E_ERROR => 'E_ERROR', // 1 @@ -585,7 +587,7 @@ protected static function checkSapiEnv(): void { // Only for cli and micro. if (!in_array(\PHP_SAPI, ['cli', 'micro'])) { - exit("Only run in command line mode \n"); + exit("Only run in command line mode\n"); } } @@ -651,8 +653,7 @@ protected static function init(): void */ protected static function resetGlobalEvent(): void { - if (static::$status === static::STATUS_STARTING && - static::$globalEvent instanceof EventInterface) { + if (static::$status === static::STATUS_STARTING && static::$globalEvent instanceof EventInterface) { static::$eventLoopClass = get_class(static::$globalEvent); static::$globalEvent = null; } @@ -755,9 +756,10 @@ public static function getEventLoop(): EventInterface /** * Get main socket resource + * * @return resource */ - public function getMainSocket() + public function getMainSocket(): mixed { return $this->mainSocket; } @@ -1069,10 +1071,10 @@ public static function getArgv(): array /** * Format status data. * - * @param $statisticsFile + * @param string $statisticsFile * @return string */ - protected static function formatStatusData($statisticsFile): string + protected static function formatStatusData(string $statisticsFile): string { static $totalRequestCache = []; if (!is_readable($statisticsFile)) { @@ -1087,7 +1089,9 @@ protected static function formatStatusData($statisticsFile): string $workerInfo = []; try { $workerInfo = unserialize($info[0], ['allowed_classes' => false]); - } catch (Throwable $exception) {} + } catch (Throwable) { + // do nothing + } ksort($workerInfo, SORT_NUMERIC); unset($info[0]); $dataWaitingSort = []; @@ -1152,7 +1156,6 @@ protected static function formatStatusData($statisticsFile): string return $statusStr; } - /** * Install signal handler. * @@ -1165,7 +1168,7 @@ protected static function installSignal(): void } $signals = [SIGINT, SIGTERM, SIGHUP, SIGTSTP, SIGQUIT, SIGUSR1, SIGUSR2, SIGIOT, SIGIO]; foreach ($signals as $signal) { - pcntl_signal($signal, [static::class, 'signalHandler'], false); + pcntl_signal($signal, static::signalHandler(...), false); } // ignore pcntl_signal(SIGPIPE, SIG_IGN, false); @@ -1185,7 +1188,7 @@ protected static function reinstallSignal(): void $signals = [SIGINT, SIGTERM, SIGHUP, SIGTSTP, SIGQUIT, SIGUSR1, SIGUSR2, SIGIOT, SIGIO]; foreach ($signals as $signal) { // Rewrite master process signal. - static::$globalEvent->onSignal($signal, [static::class, 'signalHandler']); + static::$globalEvent->onSignal($signal, static::signalHandler(...)); } } @@ -1195,7 +1198,7 @@ protected static function reinstallSignal(): void * @param int $signal * @throws Throwable */ - public static function signalHandler(int $signal): void + protected static function signalHandler(int $signal): void { switch ($signal) { // Stop. @@ -1277,8 +1280,7 @@ public static function resetStd(bool $throwException = true): void $handle = fopen(static::$stdoutFile, "a"); if ($handle) { unset($handle); - set_error_handler(function () { - }); + set_error_handler(function () {}); if ($STDOUT) { fclose($STDOUT); } @@ -1442,7 +1444,7 @@ protected static function forkWorkersForWindows(): void static::$status = static::STATUS_RUNNING; // Register shutdown function for checking errors. - register_shutdown_function([__CLASS__, 'checkErrors']); + register_shutdown_function(static::checkErrors(...)); // Create a global event loop. if (!static::$globalEvent) { @@ -1463,7 +1465,7 @@ protected static function forkWorkersForWindows(): void // Add an empty timer to prevent the event-loop from exiting. Timer::add(1000000, function (){}); - + // Display UI. static::safeEcho(str_pad($worker->name, 48) . str_pad($worker->getSocketName(), 36) . str_pad('1', 10) . " [ok]\n"); $worker->listen(); @@ -1511,13 +1513,9 @@ public static function getStartFilesForWindows(): array public static function forkOneWorkerForWindows(string $startFile): void { $startFile = realpath($startFile); - - $descriptor_spec = array( - STDIN, STDOUT, STDOUT - ); - - $pipes = array(); - $process = proc_open('"' . PHP_BINARY . '" ' . " \"$startFile\" -q", $descriptor_spec, $pipes, null, null, ['bypass_shell' => true]); + $descriptorSpec = [STDIN, STDOUT, STDOUT]; + $pipes = []; + $process = proc_open('"' . PHP_BINARY . '" ' . " \"$startFile\" -q", $descriptorSpec, $pipes, null, null, ['bypass_shell' => true]); if (empty(static::$globalEvent)) { static::$globalEvent = new Select(); @@ -1528,14 +1526,15 @@ public static function forkOneWorkerForWindows(string $startFile): void } // 保存子进程句柄 - static::$processForWindows[$startFile] = array($process, $startFile); + static::$processForWindows[$startFile] = [$process, $startFile]; } /** * check worker status for windows. + * * @return void */ - public static function checkWorkerStatusForWindows(): void + protected static function checkWorkerStatusForWindows(): void { foreach (static::$processForWindows as $processData) { $process = $processData[0]; @@ -1586,7 +1585,7 @@ protected static function forkOneWorkerForLinux(self $worker): void static::$status = static::STATUS_RUNNING; // Register shutdown function for checking errors. - register_shutdown_function(["\\Workerman\\Worker", 'checkErrors']); + register_shutdown_function(static::checkErrors(...)); // Create a global event loop. if (!static::$globalEvent) { @@ -1627,10 +1626,9 @@ protected static function forkOneWorkerForLinux(self $worker): void * * @param string $workerId * @param int $pid - * * @return false|int|string */ - protected static function getId(string $workerId, int $pid): bool|int|string + protected static function getId(string $workerId, int $pid): false|int|string { return array_search($pid, static::$idMap[$workerId]); } @@ -1677,8 +1675,7 @@ public function setUserAndGroup(): void */ protected static function setProcessTitle(string $title): void { - set_error_handler(function () { - }); + set_error_handler(function (){}); cli_set_process_title($title); restore_error_handler(); } @@ -1782,7 +1779,7 @@ protected static function monitorWorkersForLinux(): void */ protected static function monitorWorkersForWindows(): void { - Timer::add(1, "\\Workerman\\Worker::checkWorkerStatusForWindows"); + Timer::add(1, static::checkWorkerStatusForWindows(...)); static::$globalEvent->run(); } @@ -1863,7 +1860,7 @@ protected static function reload(): void posix_kill($oneWorkerPid, $sig); // If the process does not exit after stopTimeout seconds try to kill it. if (!static::getGracefulStop()) { - Timer::add(static::$stopTimeout, '\posix_kill', [$oneWorkerPid, SIGKILL], false); + Timer::add(static::$stopTimeout, posix_kill(...), [$oneWorkerPid, SIGKILL], false); } } // For child processes. else { @@ -1909,15 +1906,15 @@ public static function stopAll(int $code = 0, mixed $log = ''): void foreach ($workerPidArray as $workerPid) { // Fix exit with status 2 for php8.2 if ($sig === SIGINT && !static::$daemonize) { - Timer::add(1, '\posix_kill', [$workerPid, SIGINT], false); + Timer::add(1, posix_kill(...), [$workerPid, SIGINT], false); } else { posix_kill($workerPid, $sig); } if (!static::getGracefulStop()) { - Timer::add(ceil(static::$stopTimeout), '\posix_kill', [$workerPid, SIGKILL], false); + Timer::add(ceil(static::$stopTimeout), posix_kill(...), [$workerPid, SIGKILL], false); } } - Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning"); + Timer::add(1, static::checkIfChildRunning(...)); // Remove statistics file. if (is_file(static::$statisticsFile)) { @unlink(static::$statisticsFile); @@ -1936,8 +1933,8 @@ public static function stopAll(int $code = 0, mixed $log = ''): void // Ignore Swoole ExitException: Swoole exit. exit($code); /** @phpstan-ignore-next-line */ - } catch(\Exception $e) { - + } catch (\Exception) { + // do nothing } } } @@ -1946,7 +1943,7 @@ public static function stopAll(int $code = 0, mixed $log = ''): void /** * check if child processes is really running */ - public static function checkIfChildRunning(): void + protected static function checkIfChildRunning(): void { foreach (static::$pidMap as $workerId => $workerPidArray) { foreach ($workerPidArray as $pid => $workerPid) { @@ -2043,9 +2040,7 @@ protected static function writeStatisticsToStatusFile(): void // For child processes. gc_collect_cycles(); - if (function_exists('gc_mem_caches')) { - gc_mem_caches(); - } + gc_mem_caches(); reset(static::$workers); /** @var static $worker */ $worker = current(static::$workers); @@ -2141,7 +2136,7 @@ protected static function writeConnectionsStatisticsToStatusFile(): void * * @return void */ - public static function checkErrors(): void + protected static function checkErrors(): void { if (static::STATUS_SHUTDOWN !== static::$status) { $errorMsg = DIRECTORY_SEPARATOR === '/' ? 'Worker[' . posix_getpid() . '] process terminated' : 'Worker process terminated'; @@ -2188,6 +2183,7 @@ public static function log(mixed $msg, bool $decorated = false): void /** * Safe Echo. + * * @param string $msg * @param bool $decorated * @return bool @@ -2222,7 +2218,7 @@ public static function safeEcho(string $msg, bool $decorated = false): bool * @param resource|null $stream * @return false|resource */ - private static function outputStream($stream = null) + private static function outputStream($stream = null): mixed { if (!$stream) { $stream = static::$outputStream ?: STDOUT; @@ -2338,8 +2334,7 @@ public function listen(): void // Try to open keepalive for tcp and disable Nagle algorithm. if (function_exists('socket_import_stream') && self::BUILD_IN_TRANSPORTS[$this->transport] === 'tcp') { - set_error_handler(function () { - }); + set_error_handler(function () {}); $socket = socket_import_stream($this->mainSocket); socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); @@ -2362,8 +2357,7 @@ public function unlisten(): void { $this->pauseAccept(); if ($this->mainSocket) { - set_error_handler(function () { - }); + set_error_handler(function () {}); fclose($this->mainSocket); restore_error_handler(); $this->mainSocket = null; @@ -2426,9 +2420,9 @@ public function resumeAccept(): void // Register a listener to be notified when server socket is ready to read. if (static::$globalEvent && true === $this->pauseAccept && $this->mainSocket) { if ($this->transport !== 'udp') { - static::$globalEvent->onReadable($this->mainSocket, [$this, 'acceptTcpConnection']); + static::$globalEvent->onReadable($this->mainSocket, $this->acceptTcpConnection(...)); } else { - static::$globalEvent->onReadable($this->mainSocket, [$this, 'acceptUdpConnection']); + static::$globalEvent->onReadable($this->mainSocket, $this->acceptUdpConnection(...)); } $this->pauseAccept = false; } @@ -2511,11 +2505,10 @@ public function stop(): void * @return void * @throws Throwable */ - public function acceptTcpConnection($socket): void + protected function acceptTcpConnection(mixed $socket): void { // Accept a connection on server socket. - set_error_handler(function () { - }); + set_error_handler(function () {}); $newSocket = stream_socket_accept($socket, 0, $remoteAddress); restore_error_handler(); @@ -2553,10 +2546,9 @@ public function acceptTcpConnection($socket): void * @return bool * @throws Throwable */ - public function acceptUdpConnection($socket): bool + protected function acceptUdpConnection(mixed $socket): bool { - set_error_handler(function () { - }); + set_error_handler(function () {}); $recvBuffer = stream_socket_recvfrom($socket, UdpConnection::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress); restore_error_handler(); if (false === $recvBuffer || empty($remoteAddress)) { @@ -2632,6 +2624,6 @@ protected static function checkMasterIsAlive(int $masterPid): bool return true; } - return stripos($content, 'WorkerMan') !== false || stripos($content, 'php') !== false; + return str_contains($content, 'WorkerMan') || str_contains($content, 'php'); } }