Browse Source

Merge pull request #914 from xHeaven/master

code refactor
walkor 2 years ago
parent
commit
647dbd7475

+ 2 - 2
src/Connection/AsyncTcpConnection.php

@@ -55,7 +55,7 @@ class AsyncTcpConnection extends TcpConnection
      *
      * @var array<string,string>
      */
-    const BUILD_IN_TRANSPORTS = [
+    public const BUILD_IN_TRANSPORTS = [
         'tcp' => 'tcp',
         'udp' => 'udp',
         'unix' => 'unix',
@@ -160,7 +160,7 @@ class AsyncTcpConnection extends TcpConnection
     {
         $addressInfo = parse_url($remoteAddress);
         if (!$addressInfo) {
-            list($scheme, $this->remoteAddress) = explode(':', $remoteAddress, 2);
+            [$scheme, $this->remoteAddress] = explode(':', $remoteAddress, 2);
             if ('unix' === strtolower($scheme)) {
                 $this->remoteAddress = substr($remoteAddress, strpos($remoteAddress, '/') + 2);
             }

+ 1 - 1
src/Connection/AsyncUdpConnection.php

@@ -75,7 +75,7 @@ class AsyncUdpConnection extends UdpConnection
     public function __construct($remoteAddress, $contextOption = [])
     {
         // Get the application layer communication protocol and listening address.
-        list($scheme, $address) = explode(':', $remoteAddress, 2);
+        [$scheme, $address] = explode(':', $remoteAddress, 2);
         // Check application layer protocol class.
         if ($scheme !== 'udp') {
             $scheme = ucfirst($scheme);

+ 2 - 2
src/Connection/ConnectionInterface.php

@@ -33,14 +33,14 @@ abstract class ConnectionInterface
      *
      * @var int
      */
-    const CONNECT_FAIL = 1;
+    public const CONNECT_FAIL = 1;
 
     /**
      * Send failed.
      *
      * @var int
      */
-    const SEND_FAIL = 2;
+    public const SEND_FAIL = 2;
 
     /**
      * Statistics for status command.

+ 13 - 15
src/Connection/TcpConnection.php

@@ -63,42 +63,42 @@ class TcpConnection extends ConnectionInterface implements JsonSerializable
      *
      * @var int
      */
-    const READ_BUFFER_SIZE = 87380;
+    public const READ_BUFFER_SIZE = 87380;
 
     /**
      * Status initial.
      *
      * @var int
      */
-    const STATUS_INITIAL = 0;
+    public const STATUS_INITIAL = 0;
 
     /**
      * Status connecting.
      *
      * @var int
      */
-    const STATUS_CONNECTING = 1;
+    public const STATUS_CONNECTING = 1;
 
     /**
      * Status connection established.
      *
      * @var int
      */
-    const STATUS_ESTABLISHED = 2;
+    public const STATUS_ESTABLISHED = 2;
 
     /**
      * Status closing.
      *
      * @var int
      */
-    const STATUS_CLOSING = 4;
+    public const STATUS_CLOSING = 4;
 
     /**
      * Status closed.
      *
      * @var int
      */
-    const STATUS_CLOSED = 8;
+    public const STATUS_CLOSED = 8;
 
     /**
      * Emitted when socket connection is successfully established.
@@ -319,7 +319,7 @@ class TcpConnection extends ConnectionInterface implements JsonSerializable
      *
      * @var array
      */
-    const STATUS_TO_STRING = [
+    public const STATUS_TO_STRING = [
         self::STATUS_INITIAL => 'INITIAL',
         self::STATUS_CONNECTING => 'CONNECTING',
         self::STATUS_ESTABLISHED => 'ESTABLISHED',
@@ -686,7 +686,7 @@ class TcpConnection extends ConnectionInterface implements JsonSerializable
                 // The data is enough for a packet.
                 ++self::$statistics['total_request'];
                 // The current packet length is equal to the length of the buffer.
-                if ($one = strlen($this->recvBuffer) === $this->currentPackageLength) {
+                if ($one = (strlen($this->recvBuffer) === $this->currentPackageLength)) {
                     $oneRequestBuffer = $this->recvBuffer;
                     $this->recvBuffer = '';
                 } else {
@@ -939,13 +939,11 @@ class TcpConnection extends ConnectionInterface implements JsonSerializable
      */
     protected function checkBufferWillFull(): void
     {
-        if ($this->maxSendBufferSize <= strlen($this->sendBuffer)) {
-            if ($this->onBufferFull) {
-                try {
-                    ($this->onBufferFull)($this);
-                } catch (Throwable $e) {
-                    $this->error($e);
-                }
+        if ($this->onBufferFull && $this->maxSendBufferSize <= strlen($this->sendBuffer)) {
+            try {
+                ($this->onBufferFull)($this);
+            } catch (Throwable $e) {
+                $this->error($e);
             }
         }
     }

+ 1 - 1
src/Connection/UdpConnection.php

@@ -38,7 +38,7 @@ class UdpConnection extends ConnectionInterface implements JsonSerializable
      *
      * @var int
      */
-    const MAX_UDP_PACKAGE_SIZE = 65535;
+    public const MAX_UDP_PACKAGE_SIZE = 65535;
 
     /**
      * Transport layer protocol.

+ 5 - 8
src/Protocols/Http.php

@@ -110,7 +110,6 @@ class Http
             // Judge whether the package length exceeds the limit.
             if (strlen($buffer) >= 16384) {
                 $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
-                return 0;
             }
             return 0;
         }
@@ -132,10 +131,10 @@ class Http
         }
 
         if ($pos = stripos($header, "\r\nContent-Length: ")) {
-            $length = $length + (int)substr($header, $pos + 18, 10);
+            $length += (int)substr($header, $pos + 18, 10);
             $hasContentLength = true;
         } else if (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) {
-            $length = $length + (int)$match[1];
+            $length += (int)$match[1];
             $hasContentLength = true;
         } else {
             $hasContentLength = false;
@@ -145,11 +144,9 @@ class Http
             }
         }
 
-        if ($hasContentLength) {
-            if ($length > $connection->maxPackageSize) {
-                $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
-                return 0;
-            }
+        if ($hasContentLength && $length > $connection->maxPackageSize) {
+            $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
+            return 0;
         }
 
         if (!isset($buffer[512])) {

+ 15 - 21
src/Protocols/Http/Request.php

@@ -435,7 +435,7 @@ class Request
         $headData = explode("\r\n", $headBuffer);
         foreach ($headData as $content) {
             if (str_contains($content, ':')) {
-                list($key, $value) = explode(':', $content, 2);
+                [$key, $value] = explode(':', $content, 2);
                 $key = strtolower($key);
                 $value = ltrim($value);
             } else {
@@ -584,7 +584,7 @@ class Request
             if (!strpos($contentLine, ': ')) {
                 return 0;
             }
-            list($key, $value) = explode(': ', $contentLine);
+            [$key, $value] = explode(': ', $contentLine);
             switch (strtolower($key)) {
                 case "content-disposition":
                     // Is file data.
@@ -606,23 +606,19 @@ class Request
                         }
                         $uploadKey = $fileName;
                         // Parse upload files.
-                        $file = array_merge($file, [
-                            'name' => $match[2],
-                            'tmp_name' => $tmpFile,
-                            'size' => $size,
-                            'error' => $error
-                        ]);
-                        if (!isset($file['type'])) $file['type'] = '';
-                        break;
-                    } // Is post field.
-                    else {
-                        // Parse $POST.
-                        if (preg_match('/name="(.*?)"$/', $value, $match)) {
-                            $k = $match[1];
-                            $postEncodeString .= urlencode($k) . "=" . urlencode($boundaryValue) . '&';
+                        $file = [...$file, 'name' => $match[2], 'tmp_name' => $tmpFile, 'size' => $size, 'error' => $error];
+                        if (!isset($file['type'])) {
+                            $file['type'] = '';
                         }
-                        return $sectionEndOffset + strlen($boundary) + 2;
+                        break;
                     }
+                    // Is post field.
+                    // Parse $POST.
+                    if (preg_match('/name="(.*?)"$/', $value, $match)) {
+                        $k = $match[1];
+                        $postEncodeString .= urlencode($k) . "=" . urlencode($boundaryValue) . '&';
+                    }
+                    return $sectionEndOffset + strlen($boundary) + 2;
                 case "content-type":
                     $file['type'] = trim($value);
                     break;
@@ -731,10 +727,8 @@ class Request
         if (isset($this->data['files'])) {
             clearstatcache();
             array_walk_recursive($this->data['files'], function ($value, $key) {
-                if ($key === 'tmp_name') {
-                    if (is_file($value)) {
-                        unlink($value);
-                    }
+                if ($key === 'tmp_name' && is_file($value)) {
+                    unlink($value);
                 }
             });
         }

+ 3 - 5
src/Protocols/Http/Response.php

@@ -92,7 +92,7 @@ class Response
      *
      * @link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
      */
-    const PHRASES = [
+    public const PHRASES = [
         100 => 'Continue',
         101 => 'Switching Protocols',
         102 => 'Processing', // WebDAV; RFC 2518
@@ -414,10 +414,8 @@ class Response
             $head .= "Content-Disposition: attachment; filename=\"$baseName\"\r\n";
         }
 
-        if (!isset($headers['Last-Modified'])) {
-            if ($mtime = filemtime($file)) {
-                $head .= 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT' . "\r\n";
-            }
+        if (!isset($headers['Last-Modified']) && $mtime = filemtime($file)) {
+            $head .= 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT' . "\r\n";
         }
 
         return "$head\r\n";

+ 1 - 1
src/Protocols/Http/Session.php

@@ -320,7 +320,7 @@ class Session
                 static::$handler->write($this->sessionId, serialize($this->data));
             }
         } elseif (static::$autoUpdateTimestamp) {
-            static::refresh();
+            $this->refresh();
         }
         $this->needSave = false;
     }

+ 25 - 23
src/Protocols/Websocket.php

@@ -48,14 +48,14 @@ class Websocket
      *
      * @var string
      */
-    const BINARY_TYPE_BLOB = "\x81";
+    public const BINARY_TYPE_BLOB = "\x81";
 
     /**
      * Websocket arraybuffer type.
      *
      * @var string
      */
-    const BINARY_TYPE_ARRAYBUFFER = "\x82";
+    public const BINARY_TYPE_ARRAYBUFFER = "\x82";
 
     /**
      * Check the integrity of the package.
@@ -184,7 +184,9 @@ class Websocket
                         }
                     }
                     return 0;
-                } else if ($opcode === 0xa) {
+                }
+
+                if ($opcode === 0xa) {
                     if ($recvLen >= $currentFrameLength) {
                         $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
                         $connection->consumeRecvBuffer($currentFrameLength);
@@ -207,9 +209,9 @@ class Websocket
                     return 0;
                 }
                 return $currentFrameLength;
-            } else {
-                $connection->context->websocketCurrentFrameLength = $currentFrameLength;
             }
+
+            $connection->context->websocketCurrentFrameLength = $currentFrameLength;
         }
 
         // Received just a frame length data.
@@ -218,18 +220,20 @@ class Websocket
             $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
             $connection->context->websocketCurrentFrameLength = 0;
             return 0;
-        } // The length of the received data is greater than the length of a frame.
-        elseif ($connection->context->websocketCurrentFrameLength < $recvLen) {
+        }
+
+        // The length of the received data is greater than the length of a frame.
+        if ($connection->context->websocketCurrentFrameLength < $recvLen) {
             static::decode(substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
             $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
             $currentFrameLength = $connection->context->websocketCurrentFrameLength;
             $connection->context->websocketCurrentFrameLength = 0;
             // Continue to read next frame.
             return static::input(substr($buffer, $currentFrameLength), $connection);
-        } // The length of the received data is less than the length of a frame.
-        else {
-            return 0;
         }
+
+        // The length of the received data is less than the length of a frame.
+        return 0;
     }
 
     /**
@@ -281,13 +285,11 @@ class Websocket
             }
             $connection->context->tmpWebsocketData .= $encodeBuffer;
             // Check buffer is full.
-            if ($connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
-                if ($connection->onBufferFull) {
-                    try {
-                        ($connection->onBufferFull)($connection);
-                    } catch (Throwable $e) {
-                        Worker::stopAll(250, $e);
-                    }
+            if ($connection->onBufferFull && $connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
+                try {
+                    ($connection->onBufferFull)($connection);
+                } catch (Throwable $e) {
+                    Worker::stopAll(250, $e);
                 }
             }
             // Return empty string.
@@ -327,13 +329,13 @@ class Websocket
         if ($connection->context->websocketCurrentFrameLength) {
             $connection->context->websocketDataBuffer .= $decoded;
             return $connection->context->websocketDataBuffer;
-        } else {
-            if ($connection->context->websocketDataBuffer !== '') {
-                $decoded = $connection->context->websocketDataBuffer . $decoded;
-                $connection->context->websocketDataBuffer = '';
-            }
-            return $decoded;
         }
+
+        if ($connection->context->websocketDataBuffer !== '') {
+            $decoded = $connection->context->websocketDataBuffer . $decoded;
+            $connection->context->websocketDataBuffer = '';
+        }
+        return $decoded;
     }
 
     /**

+ 19 - 19
src/Protocols/Ws.php

@@ -49,14 +49,14 @@ class Ws
      *
      * @var string
      */
-    const BINARY_TYPE_BLOB = "\x81";
+    public const BINARY_TYPE_BLOB = "\x81";
 
     /**
      * Websocket arraybuffer type.
      *
      * @var string
      */
-    const BINARY_TYPE_ARRAYBUFFER = "\x82";
+    public const BINARY_TYPE_ARRAYBUFFER = "\x82";
 
     /**
      * Check the integrity of the package.
@@ -181,7 +181,9 @@ class Ws
                     }
                     return 0;
 
-                } else if ($opcode === 0xa) {
+                }
+
+                if ($opcode === 0xa) {
                     if ($recvLen >= $currentFrameLength) {
                         $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
                         $connection->consumeRecvBuffer($currentFrameLength);
@@ -203,9 +205,9 @@ class Ws
                     return 0;
                 }
                 return $currentFrameLength;
-            } else {
-                $connection->context->websocketCurrentFrameLength = $currentFrameLength;
             }
+
+            $connection->context->websocketCurrentFrameLength = $currentFrameLength;
         }
         // Received just a frame length data.
         if ($connection->context->websocketCurrentFrameLength === $recvLen) {
@@ -275,15 +277,13 @@ class Ws
                 }
                 return '';
             }
-            $connection->context->tmpWebsocketData = $connection->context->tmpWebsocketData . $frame;
+            $connection->context->tmpWebsocketData .= $frame;
             // Check buffer is full.
-            if ($connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
-                if ($connection->onBufferFull) {
-                    try {
-                        ($connection->onBufferFull)($connection);
-                    } catch (Throwable $e) {
-                        Worker::stopAll(250, $e);
-                    }
+            if ($connection->onBufferFull && $connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
+                try {
+                    ($connection->onBufferFull)($connection);
+                } catch (Throwable $e) {
+                    Worker::stopAll(250, $e);
                 }
             }
             return '';
@@ -312,13 +312,13 @@ class Ws
         if ($connection->context->websocketCurrentFrameLength) {
             $connection->context->websocketDataBuffer .= $decodedData;
             return $connection->context->websocketDataBuffer;
-        } else {
-            if ($connection->context->websocketDataBuffer !== '') {
-                $decodedData = $connection->context->websocketDataBuffer . $decodedData;
-                $connection->context->websocketDataBuffer = '';
-            }
-            return $decodedData;
         }
+
+        if ($connection->context->websocketDataBuffer !== '') {
+            $decodedData = $connection->context->websocketDataBuffer . $decodedData;
+            $connection->context->websocketDataBuffer = '';
+        }
+        return $decodedData;
     }
 
     /**

+ 3 - 2
src/Timer.php

@@ -23,7 +23,6 @@ use Workerman\Events\Revolt;
 use Workerman\Events\Swoole;
 use Workerman\Events\Swow;
 use function function_exists;
-use function is_callable;
 use function pcntl_alarm;
 use function pcntl_signal;
 use function time;
@@ -202,7 +201,9 @@ class Timer
                     }
                     if ($persistent && !empty(self::$status[$index])) {
                         $newRunTime = time() + $timeInterval;
-                        if (!isset(self::$tasks[$newRunTime])) self::$tasks[$newRunTime] = [];
+                        if (!isset(self::$tasks[$newRunTime])) {
+                            self::$tasks[$newRunTime] = [];
+                        }
                         self::$tasks[$newRunTime][$index] = [$taskFunc, (array)$taskArgs, $persistent, $timeInterval];
                     }
                 }

+ 18 - 18
src/Worker.php

@@ -1042,7 +1042,7 @@ class Worker
     public static function getArgv(): array
     {
         global $argv;
-        return static::$command ? array_merge($argv, explode(' ', static::$command)) : $argv;
+        return static::$command ? [...$argv, ...explode(' ', static::$command)] : $argv;
     }
 
     /**
@@ -1109,7 +1109,7 @@ class Worker
                 continue;
             }
             //$qps = isset($totalRequestCache[$pid]) ? $currentTotalRequest[$pid]
-            if (!isset($totalRequestCache[$pid]) || !isset($currentTotalRequest[$pid])) {
+            if (!isset($totalRequestCache[$pid], $currentTotalRequest[$pid])) {
                 $qps = 0;
             } else {
                 $qps = $currentTotalRequest[$pid] - $totalRequestCache[$pid];
@@ -1400,7 +1400,7 @@ class Worker
     protected static function forkWorkersForWindows(): void
     {
         $files = static::getStartFilesForWindows();
-        if (in_array('-q', static::getArgv()) || count($files) === 1) {
+        if (count($files) === 1 || in_array('-q', static::getArgv())) {
             if (count(static::$workers) > 1) {
                 static::safeEcho("@@@ Error: multi workers init in one php file are not support @@@\r\n");
                 static::safeEcho("@@@ See https://www.workerman.net/doc/workerman/faq/multi-woker-for-windows.html @@@\r\n");
@@ -1448,15 +1448,15 @@ class Worker
                 exit(250);
             }
             exit(0);
-        } else {
-            static::$globalEvent = new Select();
-            static::$globalEvent->setErrorHandler(function ($exception) {
-                static::stopAll(250, $exception);
-            });
-            Timer::init(static::$globalEvent);
-            foreach ($files as $startFile) {
-                static::forkOneWorkerForWindows($startFile);
-            }
+        }
+
+        static::$globalEvent = new Select();
+        static::$globalEvent->setErrorHandler(function ($exception) {
+            static::stopAll(250, $exception);
+        });
+        Timer::init(static::$globalEvent);
+        foreach ($files as $startFile) {
+            static::forkOneWorkerForWindows($startFile);
         }
     }
 
@@ -1771,7 +1771,7 @@ class Worker
         foreach (static::$workers as $worker) {
             $socketName = $worker->getSocketName();
             if ($worker->transport === 'unix' && $socketName) {
-                list(, $address) = explode(':', $socketName, 2);
+                [, $address] = explode(':', $socketName, 2);
                 $address = substr($address, strpos($address, '/') + 2);
                 @unlink($address);
             }
@@ -2161,7 +2161,7 @@ class Worker
      */
     public static function log(mixed $msg, bool $decorated = false): void
     {
-        $msg = $msg . "\n";
+        $msg .= "\n";
         if (!static::$daemonize) {
             static::safeEcho($msg, $decorated);
         }
@@ -2259,7 +2259,7 @@ class Worker
             && \strtolower(\php_uname('s')) !== 'darwin' // if not Mac OS
             && strpos($socketName,'unix') !== 0 // if not unix socket
             && strpos($socketName,'udp') !== 0) { // if not udp socket
-            
+
             $address = \parse_url($socketName);
             if (isset($address['host']) && isset($address['port'])) {
                 try {
@@ -2363,7 +2363,7 @@ class Worker
             return null;
         }
         // Get the application layer communication protocol and listening address.
-        list($scheme, $address) = explode(':', $this->socketName, 2);
+        [$scheme, $address] = explode(':', $this->socketName, 2);
         // Check application layer protocol class.
         if (!isset(self::BUILD_IN_TRANSPORTS[$scheme])) {
             $scheme = ucfirst($scheme);
@@ -2549,8 +2549,9 @@ class Worker
                     if ($parser && method_exists($parser, 'input')) {
                         while ($recvBuffer !== '') {
                             $len = $parser::input($recvBuffer, $connection);
-                            if ($len === 0)
+                            if ($len === 0) {
                                 return true;
+                            }
                             $package = substr($recvBuffer, 0, $len);
                             $recvBuffer = substr($recvBuffer, $len);
                             $data = $parser::decode($package, $connection);
@@ -2608,4 +2609,3 @@ class Worker
         return stripos($content, 'WorkerMan') !== false || stripos($content, 'php') !== false;
     }
 }
-