瀏覽代碼

Type restrictions

walkor 2 年之前
父節點
當前提交
ec3148bd72

+ 28 - 25
src/Connection/AsyncTcpConnection.php

@@ -14,11 +14,10 @@
 
 namespace Workerman\Connection;
 
-use Workerman\Events\EventInterface;
-use Workerman\Events\Select;
+use Throwable;
 use Workerman\Timer;
 use Workerman\Worker;
-use \Exception;
+use Exception;
 
 /**
  * AsyncTcpConnection.
@@ -28,14 +27,14 @@ class AsyncTcpConnection extends TcpConnection
     /**
      * Emitted when socket connection is successfully established.
      *
-     * @var callable|null
+     * @var ?callable
      */
     public $onConnect = null;
 
     /**
      * Emitted when websocket handshake completed (Only work when protocol is ws).
      *
-     * @var callable|null
+     * @var ?callable
      */
     public $onWebSocketConnect = null;
 
@@ -44,70 +43,70 @@ class AsyncTcpConnection extends TcpConnection
      *
      * @var string
      */
-    public $transport = 'tcp';
+    public string $transport = 'tcp';
 
     /**
      * Socks5 proxy.
      *
      * @var string
      */
-    public $proxySocks5 = '';
+    public string $proxySocks5 = '';
 
     /**
      * Http proxy.
      *
      * @var string
      */
-    public $proxyHttp = '';
+    public string $proxyHttp = '';
 
     /**
      * Status.
      *
      * @var int
      */
-    protected $status = self::STATUS_INITIAL;
+    protected int $status = self::STATUS_INITIAL;
 
     /**
      * Remote host.
      *
      * @var string
      */
-    protected $remoteHost = '';
+    protected string $remoteHost = '';
 
     /**
      * Remote port.
      *
      * @var int
      */
-    protected $remotePort = 80;
+    protected int $remotePort = 80;
 
     /**
      * Connect start time.
      *
      * @var float
      */
-    protected $connectStartTime = 0;
+    protected float $connectStartTime = 0;
 
     /**
      * Remote URI.
      *
      * @var string
      */
-    protected $remoteURI = '';
+    protected string $remoteURI = '';
 
     /**
      * Context option.
      *
      * @var array
      */
-    protected $contextOption = null;
+    protected array $contextOption = [];
 
     /**
      * Reconnect timer.
      *
      * @var int
      */
-    protected $reconnectTimer = null;
+    protected int $reconnectTimer = 0;
 
 
     /**
@@ -132,7 +131,7 @@ class AsyncTcpConnection extends TcpConnection
      * @param array $contextOption
      * @throws Exception
      */
-    public function __construct($remoteAddress, array $contextOption = [])
+    public function __construct(string $remoteAddress, array $contextOption = [])
     {
         $addressInfo = \parse_url($remoteAddress);
         if (!$addressInfo) {
@@ -195,6 +194,7 @@ class AsyncTcpConnection extends TcpConnection
      * Do connect.
      *
      * @return void
+     * @throws Throwable
      */
     public function connect()
     {
@@ -268,8 +268,9 @@ class AsyncTcpConnection extends TcpConnection
      *
      * @param int $after
      * @return void
+     * @throws Throwable
      */
-    public function reconnect($after = 0)
+    public function reconnect(int $after = 0)
     {
         $this->status = self::STATUS_INITIAL;
         static::$connections[$this->realId] = $this;
@@ -290,6 +291,7 @@ class AsyncTcpConnection extends TcpConnection
     {
         if ($this->reconnectTimer) {
             Timer::del($this->reconnectTimer);
+            $this->reconnectTimer = 0;
         }
     }
 
@@ -298,7 +300,7 @@ class AsyncTcpConnection extends TcpConnection
      *
      * @return string
      */
-    public function getRemoteHost()
+    public function getRemoteHost(): string
     {
         return $this->remoteHost;
     }
@@ -308,7 +310,7 @@ class AsyncTcpConnection extends TcpConnection
      *
      * @return string
      */
-    public function getRemoteURI()
+    public function getRemoteURI(): string
     {
         return $this->remoteURI;
     }
@@ -317,16 +319,17 @@ class AsyncTcpConnection extends TcpConnection
      * Try to emit onError callback.
      *
      * @param int $code
-     * @param string $msg
+     * @param mixed $msg
      * @return void
+     * @throws Throwable
      */
-    protected function emitError($code, $msg)
+    protected function emitError(int $code, mixed $msg)
     {
         $this->status = self::STATUS_CLOSING;
         if ($this->onError) {
             try {
                 ($this->onError)($this, $code, $msg);
-            } catch (\Throwable $e) {
+            } catch (Throwable $e) {
                 $this->error($e);
             }
         }
@@ -335,8 +338,8 @@ class AsyncTcpConnection extends TcpConnection
     /**
      * Check connection is successfully established or faild.
      *
-     * @param resource $socket
      * @return void
+     * @throws Throwable
      */
     public function checkConnection()
     {
@@ -387,7 +390,7 @@ class AsyncTcpConnection extends TcpConnection
             if ($this->onConnect) {
                 try {
                     ($this->onConnect)($this);
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     $this->error($e);
                 }
             }
@@ -395,7 +398,7 @@ class AsyncTcpConnection extends TcpConnection
             if ($this->protocol && \method_exists($this->protocol, 'onConnect')) {
                 try {
                     [$this->protocol, 'onConnect']($this);
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     $this->error($e);
                 }
             }

+ 16 - 18
src/Connection/AsyncUdpConnection.php

@@ -15,9 +15,8 @@
 namespace Workerman\Connection;
 
 use Throwable;
-use Workerman\Events\EventInterface;
 use Workerman\Worker;
-use \Exception;
+use Exception;
 
 /**
  * AsyncUdpConnection.
@@ -27,14 +26,14 @@ class AsyncUdpConnection extends UdpConnection
     /**
      * Emitted when socket connection is successfully established.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onConnect = null;
 
     /**
      * Emitted when socket connection closed.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onClose = null;
 
@@ -43,14 +42,14 @@ class AsyncUdpConnection extends UdpConnection
      *
      * @var bool
      */
-    protected $connected = false;
+    protected bool $connected = false;
 
     /**
      * Context option.
      *
      * @var array
      */
-    protected $contextOption = null;
+    protected array $contextOption = [];
 
     /**
      * Construct.
@@ -58,7 +57,7 @@ class AsyncUdpConnection extends UdpConnection
      * @param string $remoteAddress
      * @throws Exception
      */
-    public function __construct($remoteAddress, $contextOption = null)
+    public function __construct($remoteAddress, $contextOption = [])
     {
         // Get the application layer communication protocol and listening address.
         list($scheme, $address) = \explode(':', $remoteAddress, 2);
@@ -82,13 +81,14 @@ class AsyncUdpConnection extends UdpConnection
      * For udp package.
      *
      * @param resource $socket
-     * @return bool
+     * @return void
+     * @throws Throwable
      */
     public function baseRead($socket)
     {
         $recvBuffer = \stream_socket_recvfrom($socket, Worker::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress);
         if (false === $recvBuffer || empty($remoteAddress)) {
-            return false;
+            return;
         }
 
         if ($this->onMessage) {
@@ -102,17 +102,17 @@ class AsyncUdpConnection extends UdpConnection
                 $this->error($e);
             }
         }
-        return true;
     }
 
     /**
      * Sends data on the connection.
      *
-     * @param string $sendBuffer
+     * @param mixed $sendBuffer
      * @param bool $raw
      * @return void|boolean
+     * @throws Throwable
      */
-    public function send($sendBuffer, $raw = false)
+    public function send(mixed $sendBuffer, bool $raw = false)
     {
         if (false === $raw && $this->protocol) {
             $parser = $this->protocol;
@@ -127,17 +127,15 @@ class AsyncUdpConnection extends UdpConnection
         return \strlen($sendBuffer) === \stream_socket_sendto($this->socket, $sendBuffer, 0);
     }
 
-
     /**
      * Close connection.
      *
-     * @param mixed $data
+     * @param mixed|null $data
      * @param bool $raw
-     *
-     * @return bool
+     * @return void
      * @throws Throwable
      */
-    public function close($data = null, $raw = false)
+    public function close(mixed $data = null, bool $raw = false)
     {
         if ($data !== null) {
             $this->send($data, $raw);
@@ -154,13 +152,13 @@ class AsyncUdpConnection extends UdpConnection
             }
         }
         $this->onConnect = $this->onMessage = $this->onClose = $this->eventLoop = $this->errorHandler = null;
-        return true;
     }
 
     /**
      * Connect.
      *
      * @return void
+     * @throws Throwable
      */
     public function connect()
     {

+ 49 - 26
src/Connection/ConnectionInterface.php

@@ -14,6 +14,8 @@
 
 namespace Workerman\Connection;
 
+use Closure;
+use JetBrains\PhpStorm\Pure;
 use Throwable;
 use Workerman\Events\Event;
 use Workerman\Events\EventInterface;
@@ -45,7 +47,7 @@ abstract class ConnectionInterface
      *
      * @var array
      */
-    public static $statistics = [
+    public static array $statistics = [
         'connection_count' => 0,
         'total_request' => 0,
         'throw_exception' => 0,
@@ -53,111 +55,132 @@ abstract class ConnectionInterface
     ];
 
     /**
+     * Application layer protocol.
+     * The format is like this Workerman\\Protocols\\Http.
+     *
+     * @var ?class-string
+     */
+    public ?string $protocol = null;
+
+    /**
      * Emitted when data is received.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onMessage = null;
 
     /**
      * Emitted when the other end of the socket sends a FIN packet.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onClose = null;
 
     /**
      * Emitted when an error occurs with connection.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onError = null;
 
     /**
-     * @var EventInterface
+     * @var ?EventInterface
      */
-    public $eventLoop;
+    public ?EventInterface $eventLoop;
 
     /**
-     * @var \Closure
+     * @var ?callable
      */
-    public $errorHandler;
+    public $errorHandler = null;
 
     /**
      * Sends data on the connection.
      *
      * @param mixed $sendBuffer
+     * @param bool $raw
      * @return void|boolean
      */
-    abstract public function send($sendBuffer);
+    abstract public function send(mixed $sendBuffer, bool $raw = false);
 
     /**
      * Get remote IP.
      *
      * @return string
      */
-    abstract public function getRemoteIp();
+    abstract public function getRemoteIp(): string;
 
     /**
      * Get remote port.
      *
      * @return int
      */
-    abstract public function getRemotePort();
+    abstract public function getRemotePort(): int;
 
     /**
      * Get remote address.
      *
      * @return string
      */
-    abstract public function getRemoteAddress();
+    abstract public function getRemoteAddress(): string;
 
     /**
      * Get local IP.
      *
      * @return string
      */
-    abstract public function getLocalIp();
+    abstract public function getLocalIp(): string;
 
     /**
      * Get local port.
      *
      * @return int
      */
-    abstract public function getLocalPort();
+    abstract public function getLocalPort(): int;
 
     /**
      * Get local address.
      *
      * @return string
      */
-    abstract public function getLocalAddress();
+    abstract public function getLocalAddress(): string;
 
     /**
-     * Is ipv4.
+     * Close connection.
      *
-     * @return bool
+     * @param mixed|null $data
+     * @return void
      */
-    abstract public function isIPv4();
+    abstract public function close(mixed $data = null, bool $raw = false);
 
     /**
-     * Is ipv6.
+     * Is ipv4.
      *
-     * @return bool
+     * return bool.
      */
-    abstract public function isIPv6();
+    public function isIpV4(): bool
+    {
+        if ($this->transport === 'unix') {
+            return false;
+        }
+        return !str_contains($this->getRemoteIp(), ':');
+    }
 
     /**
-     * Close connection.
+     * Is ipv6.
      *
-     * @param string|null $data
-     * @return void
+     * return bool.
      */
-    abstract public function close($data = null);
+    public function isIpV6(): bool
+    {
+        if ($this->transport === 'unix') {
+            return false;
+        }
+        return str_contains($this->getRemoteIp(), ':');
+    }
 
     /**
      * @param Throwable $exception
-     * @return mixed
+     * @return void
      * @throws Throwable
      */
     public function error(Throwable $exception)

+ 96 - 128
src/Connection/TcpConnection.php

@@ -14,9 +14,10 @@
 
 namespace Workerman\Connection;
 
+use stdClass;
+use Throwable;
 use Workerman\Events\EventInterface;
 use Workerman\Protocols\Http\Request;
-use Workerman\Protocols\ProtocolInterface;
 use Workerman\Worker;
 
 /**
@@ -70,161 +71,153 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Emitted when socket connection is successfully established.
      *
-     * @var callable|null
+     * @var ?callable
      */
     public $onConnect = null;
 
     /**
      * Emitted when websocket handshake completed (Only work when protocol is ws).
      *
-     * @var callable|null
+     * @var ?callable
      */
     public $onWebSocketConnect = null;
 
     /**
      * Emitted when data is received.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onMessage = null;
 
     /**
      * Emitted when the other end of the socket sends a FIN packet.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onClose = null;
 
     /**
      * Emitted when an error occurs with connection.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onError = null;
 
     /**
      * Emitted when the send buffer becomes full.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onBufferFull = null;
 
     /**
-     * Emitted when the send buffer becomes empty.
+     * Emitted when send buffer becomes empty.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onBufferDrain = null;
 
     /**
-     * Application layer protocol.
-     * The format is like this Workerman\\Protocols\\Http.
-     *
-     * @var ProtocolInterface
-     */
-    public $protocol = null;
-
-    /**
      * Transport (tcp/udp/unix/ssl).
      *
      * @var string
      */
-    public $transport = 'tcp';
+    public string $transport = 'tcp';
 
     /**
      * Which worker belong to.
      *
-     * @var Worker
+     * @var ?Worker
      */
-    public $worker = null;
+    public ?Worker $worker = null;
 
     /**
      * Bytes read.
      *
      * @var int
      */
-    public $bytesRead = 0;
+    public int $bytesRead = 0;
 
     /**
      * Bytes written.
      *
      * @var int
      */
-    public $bytesWritten = 0;
+    public int $bytesWritten = 0;
 
     /**
      * Connection->id.
      *
      * @var int
      */
-    public $id = 0;
+    public int $id = 0;
 
     /**
      * A copy of $worker->id which used to clean up the connection in worker->connections
      *
      * @var int
      */
-    protected $realId = 0;
+    protected int $realId = 0;
 
     /**
      * Sets the maximum send buffer size for the current connection.
-     * OnBufferFull callback will be emited When the send buffer is full.
+     * OnBufferFull callback will be emited When send buffer is full.
      *
      * @var int
      */
-    public $maxSendBufferSize = 1048576;
+    public int $maxSendBufferSize = 1048576;
     
     /**
      * Context.
      *
-     * @var object
+     * @var ?stdClass
      */
-    public $context;
+    public ?stdClass $context = null;
 
     /**
      * @var array
      */
-    public $headers = [];
+    public array $headers = [];
 
     /**
-     * @var object
+     * @var ?Request
      */
-    public $request;
+    public ?Request $request = null;
 
     /**
      * Default send buffer size.
      *
      * @var int
      */
-    public static $defaultMaxSendBufferSize = 1048576;
+    public static int $defaultMaxSendBufferSize = 1048576;
 
     /**
      * Sets the maximum acceptable packet size for the current connection.
      *
      * @var int
      */
-    public $maxPackageSize = 1048576;
+    public int $maxPackageSize = 1048576;
 
     /**
      * Default maximum acceptable packet size.
      *
      * @var int
      */
-    public static $defaultMaxPackageSize = 10485760;
+    public static int $defaultMaxPackageSize = 10485760;
 
     /**
      * Id recorder.
      *
      * @var int
      */
-    protected static $idRecorder = 1;
+    protected static int $idRecorder = 1;
 
     /**
      * Cache.
      *
      * @var bool.
      */
-    protected static $enableCache = true;
+    protected static bool $enableCache = true;
 
     /**
      * Socket
@@ -238,63 +231,63 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @var string
      */
-    protected $sendBuffer = '';
+    protected string $sendBuffer = '';
 
     /**
      * Receive buffer.
      *
      * @var string
      */
-    protected $recvBuffer = '';
+    protected string $recvBuffer = '';
 
     /**
      * Current package length.
      *
      * @var int
      */
-    protected $currentPackageLength = 0;
+    protected int $currentPackageLength = 0;
 
     /**
      * Connection status.
      *
      * @var int
      */
-    protected $status = self::STATUS_ESTABLISHED;
+    protected int $status = self::STATUS_ESTABLISHED;
 
     /**
      * Remote address.
      *
      * @var string
      */
-    protected $remoteAddress = '';
+    protected string $remoteAddress = '';
 
     /**
      * Is paused.
      *
      * @var bool
      */
-    protected $isPaused = false;
+    protected bool $isPaused = false;
 
     /**
      * SSL handshake completed or not.
      *
      * @var bool
      */
-    protected $sslHandshakeCompleted = false;
+    protected bool $sslHandshakeCompleted = false;
 
     /**
      * All connection instances.
      *
      * @var array
      */
-    public static $connections = [];
+    public static array $connections = [];
 
     /**
      * Status to string.
      *
      * @var array
      */
-    public static $statusToString = [
+    const STATUS_TO_STRING = [
         self::STATUS_INITIAL => 'INITIAL',
         self::STATUS_CONNECTING => 'CONNECTING',
         self::STATUS_ESTABLISHED => 'ESTABLISHED',
@@ -305,10 +298,11 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Construct.
      *
+     * @param EventInterface $eventLoop
      * @param resource $socket
      * @param string $remoteAddress
      */
-    public function __construct($eventLoop, $socket, $remoteAddress = '')
+    public function __construct(EventInterface $eventLoop, $socket, string $remoteAddress = '')
     {
         ++self::$statistics['connection_count'];
         $this->id = $this->realId = self::$idRecorder++;
@@ -327,7 +321,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         $this->maxPackageSize = self::$defaultMaxPackageSize;
         $this->remoteAddress = $remoteAddress;
         static::$connections[$this->id] = $this;
-        $this->context = new \stdClass;
+        $this->context = new stdClass;
     }
 
     /**
@@ -337,12 +331,12 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return int|string
      */
-    public function getStatus($rawOutput = true)
+    public function getStatus(bool $rawOutput = true): int|string
     {
         if ($rawOutput) {
             return $this->status;
         }
-        return self::$statusToString[$this->status];
+        return self::STATUS_TO_STRING[$this->status];
     }
 
     /**
@@ -351,8 +345,9 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * @param mixed $sendBuffer
      * @param bool $raw
      * @return bool|void
+     * @throws Throwable
      */
-    public function send($sendBuffer, $raw = false)
+    public function send(mixed $sendBuffer, bool $raw = false)
     {
         if ($this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) {
             return false;
@@ -389,7 +384,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
             $len = 0;
             try {
                 $len = @\fwrite($this->socket, $sendBuffer);
-            } catch (\Throwable $e) {
+            } catch (Throwable $e) {
                 Worker::log($e);
             }
             // send successful.
@@ -408,7 +403,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                     if ($this->onError) {
                         try {
                             ($this->onError)($this, static::SEND_FAIL, 'client closed');
-                        } catch (\Throwable $e) {
+                        } catch (Throwable $e) {
                             $this->error($e);
                         }
                     }
@@ -418,7 +413,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                 $this->sendBuffer = $sendBuffer;
             }
             $this->eventLoop->onWritable($this->socket, [$this, 'baseWrite']);
-            // Check if the send buffer will be full.
+            // Check if send buffer will be full.
             $this->checkBufferWillFull();
             return;
         }
@@ -429,7 +424,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         }
 
         $this->sendBuffer .= $sendBuffer;
-        // Check if the send buffer is full.
+        // Check if send buffer is full.
         $this->checkBufferWillFull();
     }
 
@@ -438,7 +433,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getRemoteIp()
+    public function getRemoteIp(): string
     {
         $pos = \strrpos($this->remoteAddress, ':');
         if ($pos) {
@@ -452,7 +447,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return int
      */
-    public function getRemotePort()
+    public function getRemotePort(): int
     {
         if ($this->remoteAddress) {
             return (int)\substr(\strrchr($this->remoteAddress, ':'), 1);
@@ -465,7 +460,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getRemoteAddress()
+    public function getRemoteAddress(): string
     {
         return $this->remoteAddress;
     }
@@ -475,7 +470,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getLocalIp()
+    public function getLocalIp(): string
     {
         $address = $this->getLocalAddress();
         $pos = \strrpos($address, ':');
@@ -490,7 +485,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return int
      */
-    public function getLocalPort()
+    public function getLocalPort(): int
     {
         $address = $this->getLocalAddress();
         $pos = \strrpos($address, ':');
@@ -505,7 +500,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getLocalAddress()
+    public function getLocalAddress(): string
     {
         if (!\is_resource($this->socket)) {
             return '';
@@ -518,48 +513,22 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return integer
      */
-    public function getSendBufferQueueSize()
+    public function getSendBufferQueueSize(): int
     {
         return \strlen($this->sendBuffer);
     }
 
     /**
-     * Get recv buffer queue size.
+     * Get receive buffer queue size.
      *
      * @return integer
      */
-    public function getRecvBufferQueueSize()
+    public function getRecvBufferQueueSize(): int
     {
         return \strlen($this->recvBuffer);
     }
 
     /**
-     * Is ipv4.
-     *
-     * return bool.
-     */
-    public function isIpV4()
-    {
-        if ($this->transport === 'unix') {
-            return false;
-        }
-        return \strpos($this->getRemoteIp(), ':') === false;
-    }
-
-    /**
-     * Is ipv6.
-     *
-     * return bool.
-     */
-    public function isIpV6()
-    {
-        if ($this->transport === 'unix') {
-            return false;
-        }
-        return \strpos($this->getRemoteIp(), ':') !== false;
-    }
-
-    /**
      * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
      *
      * @return void
@@ -574,6 +543,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * Resumes reading after a call to pauseRecv.
      *
      * @return void
+     * @throws Throwable
      */
     public function resumeRecv()
     {
@@ -591,8 +561,9 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * @param resource $socket
      * @param bool $checkEof
      * @return void
+     * @throws Throwable
      */
-    public function baseRead($socket, $checkEof = true)
+    public function baseRead($socket, bool $checkEof = true)
     {
         static $requests = [];
         // SSL handshake.
@@ -610,7 +581,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         $buffer = '';
         try {
             $buffer = @\fread($socket, self::READ_BUFFER_SIZE);
-        } catch (\Throwable $e) {
+        } catch (Throwable $e) {
         }
 
         // Check connection closed.
@@ -634,7 +605,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                     }
                     try {
                         ($this->onMessage)($this, $request);
-                    } catch (\Throwable $e) {
+                    } catch (Throwable $e) {
                         $this->error($e);
                     }
                     return;
@@ -658,7 +629,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                     // Get current package length.
                     try {
                         $this->currentPackageLength = $this->protocol::input($this->recvBuffer, $this);
-                    } catch (\Throwable $e) {
+                    } catch (Throwable $e) {
                     }
                     // The packet length is unknown.
                     if ($this->currentPackageLength === 0) {
@@ -685,7 +656,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                 } else {
                     // Get a full package from the buffer.
                     $oneRequestBuffer = \substr($this->recvBuffer, 0, $this->currentPackageLength);
-                    // Remove the current package from the receive buffer.
+                    // Remove the current package from receive buffer.
                     $this->recvBuffer = \substr($this->recvBuffer, $this->currentPackageLength);
                 }
                 // Reset the current packet length to 0.
@@ -700,7 +671,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                         }
                     }
                     ($this->onMessage)($this, $request);
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     $this->error($e);
                 }
             }
@@ -715,7 +686,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         ++self::$statistics['total_request'];
         try {
             ($this->onMessage)($this, $this->recvBuffer);
-        } catch (\Throwable $e) {
+        } catch (Throwable $e) {
             $this->error($e);
         }
         // Clean receive buffer.
@@ -725,7 +696,8 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Base write handler.
      *
-     * @return void|bool
+     * @return void
+     * @throws Throwable
      */
     public function baseWrite()
     {
@@ -736,26 +708,26 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
             } else {
                 $len = @\fwrite($this->socket, $this->sendBuffer);
             }
-        } catch (\Throwable $e) {}
+        } catch (Throwable $e) {}
         if ($len === \strlen($this->sendBuffer)) {
             $this->bytesWritten += $len;
             $this->eventLoop->offWritable($this->socket);
             $this->sendBuffer = '';
-            // Try to emit onBufferDrain callback when the send buffer becomes empty.
+            // Try to emit onBufferDrain callback when send buffer becomes empty.
             if ($this->onBufferDrain) {
                 try {
                     ($this->onBufferDrain)($this);
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     $this->error($e);
                 }
             }
             if ($this->status === self::STATUS_CLOSING) {
                 if ($this->context->streamSending) {
-                    return true;
+                    return;
                 }
                 $this->destroy();
             }
-            return true;
+            return;
         }
         if ($len > 0) {
             $this->bytesWritten += $len;
@@ -770,9 +742,10 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * SSL handshake.
      *
      * @param resource $socket
-     * @return bool
+     * @return bool|int
+     * @throws Throwable
      */
-    public function doSslHandshake($socket)
+    public function doSslHandshake($socket): bool|int
     {
         if (\feof($socket)) {
             $this->destroy();
@@ -812,13 +785,6 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
             // There isn't enough data and should try again.
             return 0;
         }
-        if (isset($this->onSslHandshake)) {
-            try {
-                ($this->onSslHandshake)($this);
-            } catch (\Throwable $e) {
-                $this->error($e);
-            }
-        }
         return true;
     }
 
@@ -851,7 +817,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * @param int $length
      * @return void
      */
-    public function consumeRecvBuffer($length)
+    public function consumeRecvBuffer(int $length)
     {
         $this->recvBuffer = \substr($this->recvBuffer, $length);
     }
@@ -859,11 +825,12 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Close connection.
      *
-     * @param mixed $data
+     * @param mixed|null $data
      * @param bool $raw
      * @return void
+     * @throws Throwable
      */
-    public function close($data = null, $raw = false)
+    public function close(mixed $data = null, bool $raw = false)
     {
         if ($this->status === self::STATUS_CONNECTING) {
             $this->destroy();
@@ -898,9 +865,10 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     }
 
     /**
-     * Check whether the send buffer will be full.
+     * Check whether send buffer will be full.
      *
      * @return void
+     * @throws Throwable
      */
     protected function checkBufferWillFull()
     {
@@ -908,7 +876,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
             if ($this->onBufferFull) {
                 try {
                     ($this->onBufferFull)($this);
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     $this->error($e);
                 }
             }
@@ -919,15 +887,16 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * Whether send buffer is full.
      *
      * @return bool
+     * @throws Throwable
      */
-    protected function bufferIsFull()
+    protected function bufferIsFull(): bool
     {
         // Buffer has been marked as full but still has data to send then the packet is discarded.
         if ($this->maxSendBufferSize <= \strlen($this->sendBuffer)) {
             if ($this->onError) {
                 try {
                     ($this->onError)($this, static::SEND_FAIL, 'send buffer full and drop package');
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     $this->error($e);
                 }
             }
@@ -941,7 +910,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return bool
      */
-    public function bufferIsEmpty()
+    public function bufferIsEmpty(): bool
     {
         return empty($this->sendBuffer);
     }
@@ -950,7 +919,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * Destroy connection.
      *
      * @return void
-     * @throws \Throwable
+     * @throws Throwable
      */
     public function destroy()
     {
@@ -965,7 +934,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         // Close socket.
         try {
             @\fclose($this->socket);
-        } catch (\Throwable $e) {
+        } catch (Throwable $e) {
         }
 
         $this->status = self::STATUS_CLOSED;
@@ -973,7 +942,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         if ($this->onClose) {
             try {
                 ($this->onClose)($this);
-            } catch (\Throwable $e) {
+            } catch (Throwable $e) {
                 $this->error($e);
             }
         }
@@ -981,7 +950,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         if ($this->protocol && \method_exists($this->protocol, 'onClose')) {
             try {
                 ([$this->protocol, 'onClose'])($this);
-            } catch (\Throwable $e) {
+            } catch (Throwable $e) {
                 $this->error($e);
             }
         }
@@ -1004,18 +973,17 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @param mixed $value
      */
-    public static function enableCache($value)
+    public static function enableCache(bool $value = true)
     {
-        static::$enableCache = (bool)$value;
+        static::$enableCache = $value;
     }
     
     /**
      * Get the json_encode information.
      *
-     * @return mixed
+     * @return array
      */
-    #[\ReturnTypeWillChange]
-    public function jsonSerialize()
+    public function jsonSerialize(): array
     {        
         return [
             'id' => $this->id,

+ 17 - 54
src/Connection/UdpConnection.php

@@ -14,41 +14,31 @@
 
 namespace Workerman\Connection;
 
-use Workerman\Protocols\ProtocolInterface;
-
 /**
  * UdpConnection.
  */
 class UdpConnection extends ConnectionInterface implements \JsonSerializable
 {
     /**
-     * Application layer protocol.
-     * The format is like this Workerman\\Protocols\\Http.
-     *
-     * @var ProtocolInterface
-     */
-    public $protocol = null;
-
-    /**
      * Transport layer protocol.
      *
      * @var string
      */
-    public $transport = 'udp';
+    public string $transport = 'udp';
 
     /**
      * Udp socket.
      *
      * @var resource
      */
-    protected $socket = null;
+    protected $socket;
 
     /**
      * Remote address.
      *
      * @var string
      */
-    protected $remoteAddress = '';
+    protected string $remoteAddress = '';
 
     /**
      * Construct.
@@ -56,7 +46,7 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      * @param resource $socket
      * @param string $remoteAddress
      */
-    public function __construct($socket, $remoteAddress)
+    public function __construct($socket, string $remoteAddress)
     {
         $this->socket = $socket;
         $this->remoteAddress = $remoteAddress;
@@ -65,11 +55,11 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Sends data on the connection.
      *
-     * @param string $sendBuffer
+     * @param mixed $sendBuffer
      * @param bool $raw
      * @return void|boolean
      */
-    public function send($sendBuffer, $raw = false)
+    public function send(mixed $sendBuffer, bool $raw = false)
     {
         if (false === $raw && $this->protocol) {
             $parser = $this->protocol;
@@ -86,7 +76,7 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getRemoteIp()
+    public function getRemoteIp(): string
     {
         $pos = \strrpos($this->remoteAddress, ':');
         if ($pos) {
@@ -100,7 +90,7 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return int
      */
-    public function getRemotePort()
+    public function getRemotePort(): int
     {
         if ($this->remoteAddress) {
             return (int)\substr(\strrchr($this->remoteAddress, ':'), 1);
@@ -113,7 +103,7 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getRemoteAddress()
+    public function getRemoteAddress(): string
     {
         return $this->remoteAddress;
     }
@@ -123,7 +113,7 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getLocalIp()
+    public function getLocalIp(): string
     {
         $address = $this->getLocalAddress();
         $pos = \strrpos($address, ':');
@@ -138,7 +128,7 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return int
      */
-    public function getLocalPort()
+    public function getLocalPort(): int
     {
         $address = $this->getLocalAddress();
         $pos = \strrpos($address, ':');
@@ -153,51 +143,24 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      *
      * @return string
      */
-    public function getLocalAddress()
+    public function getLocalAddress(): string
     {
         return (string)@\stream_socket_get_name($this->socket, false);
     }
 
-    /**
-     * Is ipv4.
-     *
-     * @return bool.
-     */
-    public function isIpV4()
-    {
-        if ($this->transport === 'unix') {
-            return false;
-        }
-        return \strpos($this->getRemoteIp(), ':') === false;
-    }
-
-    /**
-     * Is ipv6.
-     *
-     * @return bool.
-     */
-    public function isIpV6()
-    {
-        if ($this->transport === 'unix') {
-            return false;
-        }
-        return \strpos($this->getRemoteIp(), ':') !== false;
-    }
 
     /**
      * Close connection.
      *
-     * @param mixed $data
-     * @param bool $raw
-     * @return bool
+     * @param mixed|null $data
+     * @return void
      */
-    public function close($data = null, $raw = false)
+    public function close(mixed $data = null, bool $raw = false)
     {
         if ($data !== null) {
             $this->send($data, $raw);
         }
         $this->eventLoop = $this->errorHandler = null;
-        return true;
     }
 
     /**
@@ -211,11 +174,11 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
     }
     
     /**
-     * Get the json_encode informattion.
+     * Get the json_encode information.
      *
      * @return array
      */
-    public function jsonSerialize()
+    public function jsonSerialize(): array
     {
         return [
             'transport' => $this->transport,

+ 28 - 22
src/Events/Ev.php

@@ -26,50 +26,50 @@ class Ev implements EventInterface
      *
      * @var array
      */
-    protected $readEvents = [];
+    protected array $readEvents = [];
 
     /**
      * All listeners for write event.
      *
      * @var array
      */
-    protected $writeEvents = [];
+    protected array $writeEvents = [];
 
     /**
      * Event listeners of signal.
      *
      * @var array
      */
-    protected $eventSignal = [];
+    protected array $eventSignal = [];
 
     /**
      * All timer event listeners.
      *
      * @var array
      */
-    protected $eventTimer = [];
+    protected array $eventTimer = [];
 
     /**
-     * @var Closure || null
+     * @var ?callable
      */
-    protected $errorHandler;
+    protected $errorHandler = null;
 
     /**
      * Timer id.
      *
      * @var int
      */
-    protected static $timerId = 1;
+    protected static int $timerId = 1;
 
     /**
      * {@inheritdoc}
      */
-    public function delay(float $delay, $func, $args = [])
+    public function delay(float $delay, callable $func, array $args = []): int
     {
         $timerId = self::$timerId;
         $event = new \EvTimer($delay, 0, function () use ($func, $args, $timerId) {
             unset($this->eventTimer[$timerId]);
-            $func(...(array)$args);
+            $func(...$args);
         });
         $this->eventTimer[self::$timerId] = $event;
         return self::$timerId++;
@@ -78,7 +78,7 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offDelay($timerId)
+    public function offDelay(int $timerId): bool
     {
         if (isset($this->eventTimer[$timerId])) {
             $this->eventTimer[$timerId]->stop();
@@ -91,7 +91,7 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offRepeat($timerId)
+    public function offRepeat(int $timerId): bool
     {
         return $this->offDelay($timerId);
     }
@@ -99,10 +99,10 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function repeat(float $interval, $func, $args = [])
+    public function repeat(float $interval, callable $func, array $args = []): int
     {
         $event = new \EvTimer($interval, $interval, function () use ($func, $args) {
-            $func(...(array)$args);
+            $func(...$args);
         });
         $this->eventTimer[self::$timerId] = $event;
         return self::$timerId++;
@@ -111,7 +111,7 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function onReadable($stream, $func)
+    public function onReadable($stream, callable $func)
     {
         $fdKey = (int)$stream;
         $event = new \EvIo($stream, \Ev::READ, function () use ($func, $stream) {
@@ -123,19 +123,21 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offReadable($stream)
+    public function offReadable($stream): bool
     {
         $fdKey = (int)$stream;
         if (isset($this->readEvents[$fdKey])) {
             $this->readEvents[$fdKey]->stop();
             unset($this->readEvents[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onWritable($stream, $func)
+    public function onWritable($stream, callable $func)
     {
         $fdKey = (int)$stream;
         $event = new \EvIo($stream, \Ev::WRITE, function () use ($func, $stream) {
@@ -147,19 +149,21 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offWritable($stream)
+    public function offWritable($stream): bool
     {
         $fdKey = (int)$stream;
         if (isset($this->writeEvents[$fdKey])) {
             $this->writeEvents[$fdKey]->stop();
             unset($this->writeEvents[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onSignal($signal, $func)
+    public function onSignal(int $signal, callable $func)
     {
         $event = new \EvSignal($signal, function () use ($func, $signal) {
             $func($signal);
@@ -170,12 +174,14 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offSignal($signal)
+    public function offSignal(int $signal): bool
     {
         if (isset($this->eventSignal[$signal])) {
             $this->eventSignal[$signal]->stop();
             unset($this->eventSignal[$signal]);
+            return true;
         }
+        return false;
     }
 
     /**
@@ -208,7 +214,7 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getTimerCount()
+    public function getTimerCount(): int
     {
         return \count($this->eventTimer);
     }
@@ -216,7 +222,7 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function setErrorHandler($errorHandler)
+    public function setErrorHandler(callable $errorHandler)
     {
         $this->errorHandler = $errorHandler;
     }
@@ -224,7 +230,7 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getErrorHandler()
+    public function getErrorHandler(): ?callable
     {
         return $this->errorHandler;
     }

+ 34 - 30
src/Events/Event.php

@@ -15,6 +15,7 @@
 namespace Workerman\Events;
 
 use Throwable;
+use EventBase;
 
 /**
  * libevent eventloop
@@ -23,51 +24,51 @@ class Event implements EventInterface
 {
     /**
      * Event base.
-     * @var object
+     * @var EventBase
      */
-    protected $eventBase = null;
+    protected $eventBase;
 
     /**
      * All listeners for read event.
      * @var array
      */
-    protected $readEvents = [];
+    protected array $readEvents = [];
 
     /**
      * All listeners for write event.
      * @var array
      */
-    protected $writeEvents = [];
+    protected array $writeEvents = [];
 
     /**
      * Event listeners of signal.
      * @var array
      */
-    protected $eventSignal = [];
+    protected array $eventSignal = [];
 
     /**
      * All timer event listeners.
      * [func, args, event, flag, time_interval]
      * @var array
      */
-    protected $eventTimer = [];
+    protected array $eventTimer = [];
 
     /**
      * Timer id.
      * @var int
      */
-    protected $timerId = 0;
+    protected int $timerId = 0;
 
     /**
      * Event class name.
      * @var string
      */
-    protected $eventClassName = '';
+    protected string $eventClassName = '';
 
     /**
-     * @var Closure || null
+     * @var ?callable
      */
-    protected $errorHandler;
+    protected $errorHandler = null;
 
     /**
      * Construct.
@@ -92,7 +93,7 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function delay(float $delay, $func, $args = [])
+    public function delay(float $delay, callable $func, array $args = []): int
     {
         $className = $this->eventClassName;
         $timerId = $this->timerId++;
@@ -113,7 +114,7 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offDelay($timerId)
+    public function offDelay(int $timerId): bool
     {
         if (isset($this->eventTimer[$timerId])) {
             $this->eventTimer[$timerId]->del();
@@ -126,7 +127,7 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offRepeat($timerId)
+    public function offRepeat(int $timerId): bool
     {
         return $this->offDelay($timerId);
     }
@@ -134,7 +135,7 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function repeat(float $interval, $func, $args = [])
+    public function repeat(float $interval, callable $func, array $args = []): int
     {
         $className = $this->eventClassName;
         $timerId = $this->timerId++;
@@ -155,82 +156,85 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function onReadable($stream, $func)
+    public function onReadable($stream, callable $func)
     {
         $className = $this->eventClassName;
         $fdKey = (int)$stream;
         $event = new $this->eventClassName($this->eventBase, $stream, $className::READ | $className::PERSIST, $func, $stream);
         if (!$event || !$event->add()) {
-            return false;
+            return;
         }
         $this->readEvents[$fdKey] = $event;
-        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offReadable($stream)
+    public function offReadable($stream): bool
     {
         $fdKey = (int)$stream;
         if (isset($this->readEvents[$fdKey])) {
             $this->readEvents[$fdKey]->del();
             unset($this->readEvents[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onWritable($stream, $func)
+    public function onWritable($stream, callable $func)
     {
         $className = $this->eventClassName;
         $fdKey = (int)$stream;
         $event = new $this->eventClassName($this->eventBase, $stream, $className::WRITE | $className::PERSIST, $func, $stream);
         if (!$event || !$event->add()) {
-            return false;
+            return;
         }
         $this->writeEvents[$fdKey] = $event;
-        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offWritable($stream)
+    public function offWritable($stream): bool
     {
         $fdKey = (int)$stream;
         if (isset($this->writeEvents[$fdKey])) {
             $this->writeEvents[$fdKey]->del();
             unset($this->writeEvents[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onSignal($signal, $func)
+    public function onSignal(int $signal, callable $func)
     {
         $className = $this->eventClassName;
-        $fdKey = (int)$signal;
+        $fdKey = $signal;
         $event = $className::signal($this->eventBase, $signal, $func);
         if (!$event || !$event->add()) {
-            return false;
+            return;
         }
         $this->eventSignal[$fdKey] = $event;
-        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offSignal($signal)
+    public function offSignal(int $signal): bool
     {
-        $fdKey = (int)$signal;
+        $fdKey = $signal;
         if (isset($this->eventSignal[$fdKey])) {
             $this->eventSignal[$fdKey]->del();
             unset($this->eventSignal[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
@@ -263,7 +267,7 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getTimerCount()
+    public function getTimerCount(): int
     {
         return \count($this->eventTimer);
     }
@@ -279,7 +283,7 @@ class Event implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getErrorHandler()
+    public function getErrorHandler(): ?callable
     {
         return $this->errorHandler;
     }

+ 35 - 35
src/Events/EventInterface.php

@@ -18,79 +18,79 @@ interface EventInterface
     /**
      * Delay the execution of a callback.
      * @param float $delay
-     * @param $func
-     * @param $args
-     * @return int|bool
+     * @param callable $func
+     * @param array $args
+     * @return int
      */
-    public function delay(float $delay, $func, $args = []);
+    public function delay(float $delay, callable $func, array $args = []): int;
 
     /**
      * Delete a delay timer.
-     * @param $timerId
+     * @param int $timerId
      * @return bool
      */
-    public function offDelay($timerId);
+    public function offDelay(int $timerId): bool;
 
     /**
      * Repeatedly execute a callback.
      * @param float $interval
-     * @param $func
-     * @param $args
-     * @return int|bool
+     * @param callable $func
+     * @param array $args
+     * @return int
      */
-    public function repeat(float $interval, $func, $args = []);
+    public function repeat(float $interval, callable $func, array $args = []): int;
 
     /**
      * Delete a repeat timer.
-     * @param $timerId
+     * @param int $timerId
      * @return bool
      */
-    public function offRepeat($timerId);
+    public function offRepeat(int $timerId): bool;
 
     /**
      * Execute a callback when a stream resource becomes readable or is closed for reading.
-     * @param $stream
-     * @param $func
+     * @param resource $stream
+     * @param callable $func
      * @return void
      */
-    public function onReadable($stream, $func);
+    public function onReadable($stream, callable $func);
 
     /**
      * Cancel a callback of stream readable.
-     * @param $stream
-     * @return void
+     * @param resource $stream
+     * @return bool
      */
-    public function offReadable($stream);
+    public function offReadable($stream): bool;
 
     /**
      * Execute a callback when a stream resource becomes writable or is closed for writing.
-     * @param $stream
-     * @param $func
+     * @param resource $stream
+     * @param callable $func
      * @return void
      */
-    public function onWritable($stream, $func);
+    public function onWritable($stream, callable $func);
 
     /**
      * Cancel a callback of stream writable.
-     * @param $stream
-     * @return void
+     * @param resource $stream
+     * @return bool
      */
-    public function offWritable($stream);
+    public function offWritable($stream): bool;
 
     /**
      * Execute a callback when a signal is received.
-     * @param $signal
-     * @param $func
+     * @param int $signal
+     * @param callable $func
      * @return void
      */
-    public function onSignal($signal, $func);
+    public function onSignal(int $signal, callable $func);
 
     /**
      * Cancel a callback of signal.
-     * @param $signal
-     * @return void
+     * @param int $signal
+     * @return bool
      */
-    public function offSignal($signal);
+    public function offSignal(int $signal): bool;
 
     /**
      * Delete all timer.
@@ -114,18 +114,18 @@ interface EventInterface
      * Get Timer count.
      * @return int
      */
-    public function getTimerCount();
+    public function getTimerCount(): int;
 
     /**
      * Set error handler
-     * @param $errorHandler
+     * @param callable $errorHandler
      * @return void
      */
-    public function setErrorHandler($errorHandler);
+    public function setErrorHandler(callable $errorHandler);
 
     /**
      * Get error handler
-     * @return null|\Closure(\Throwable)
+     * @return ?callable(Throwable)
      */
-    public function getErrorHandler();
+    public function getErrorHandler(): ?callable;
 }

+ 28 - 24
src/Events/Revolt.php

@@ -25,37 +25,37 @@ class Revolt implements EventInterface
     /**
      * @var Driver
      */
-    protected $driver = null;
+    protected Driver $driver;
 
     /**
      * All listeners for read event.
      * @var array
      */
-    protected $readEvents = [];
+    protected array $readEvents = [];
 
     /**
      * All listeners for write event.
      * @var array
      */
-    protected $writeEvents = [];
+    protected array $writeEvents = [];
 
     /**
      * Event listeners of signal.
      * @var array
      */
-    protected $eventSignal = [];
+    protected array $eventSignal = [];
 
     /**
      * Event listeners of timer.
      * @var array
      */
-    protected $eventTimer = [];
+    protected array $eventTimer = [];
 
     /**
      * Timer id.
      * @var int
      */
-    protected $timerId = 1;
+    protected int $timerId = 1;
 
     /**
      * Construct.
@@ -68,7 +68,7 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function driver()
+    public function driver(): Driver
     {
         return $this->driver;
     }
@@ -98,9 +98,8 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function delay(float $delay, $func, $args = [])
+    public function delay(float $delay, callable $func, array $args = []): int
     {
-        $args = (array)$args;
         $timerId = $this->timerId++;
         $closure = function () use ($func, $args, $timerId) {
             unset($this->eventTimer[$timerId]);
@@ -114,9 +113,8 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function repeat(float $interval, $func, $args = [])
+    public function repeat(float $interval, callable $func, array $args = []): int
     {
-        $args = (array)$args;
         $timerId = $this->timerId++;
         $closure = function () use ($func, $args) {
             $func(...$args);
@@ -129,7 +127,7 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function onReadable($stream, $func)
+    public function onReadable($stream, callable $func)
     {
         $fdKey = (int)$stream;
         if (isset($this->readEvents[$fdKey])) {
@@ -145,19 +143,21 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offReadable($stream)
+    public function offReadable($stream): bool
     {
         $fdKey = (int)$stream;
         if (isset($this->readEvents[$fdKey])) {
             $this->driver->cancel($this->readEvents[$fdKey]);
             unset($this->readEvents[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onWritable($stream, $func)
+    public function onWritable($stream, callable $func)
     {
         $fdKey = (int)$stream;
         if (isset($this->writeEvents[$fdKey])) {
@@ -172,21 +172,23 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offWritable($stream)
+    public function offWritable($stream): bool
     {
         $fdKey = (int)$stream;
         if (isset($this->writeEvents[$fdKey])) {
             $this->driver->cancel($this->writeEvents[$fdKey]);
             unset($this->writeEvents[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onSignal($signal, $func)
+    public function onSignal(int $signal, callable $func)
     {
-        $fdKey = (int)$signal;
+        $fdKey = $signal;
         if (isset($this->eventSignal[$fdKey])) {
             $this->driver->cancel($this->eventSignal[$fdKey]);
             unset($this->eventSignal[$fdKey]);
@@ -199,19 +201,21 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offSignal($signal)
+    public function offSignal(int $signal): bool
     {
-        $fdKey = (int)$signal;
+        $fdKey = $signal;
         if (isset($this->eventSignal[$fdKey])) {
             $this->driver->cancel($this->eventSignal[$fdKey]);
             unset($this->eventSignal[$fdKey]);
+            return true;
         }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offDelay($timerId)
+    public function offDelay(int $timerId): bool
     {
         if (isset($this->eventTimer[$timerId])) {
             $this->driver->cancel($this->eventTimer[$timerId]);
@@ -224,7 +228,7 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offRepeat($timerId)
+    public function offRepeat(int $timerId): bool
     {
         return $this->offDelay($timerId);
     }
@@ -243,7 +247,7 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getTimerCount()
+    public function getTimerCount(): int
     {
         return \count($this->eventTimer);
     }
@@ -251,7 +255,7 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function setErrorHandler($errorHandler)
+    public function setErrorHandler(callable $errorHandler)
     {
         $this->driver->setErrorHandler($errorHandler);
     }
@@ -259,7 +263,7 @@ class Revolt implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getErrorHandler()
+    public function getErrorHandler(): ?callable
     {
         return $this->driver->getErrorHandler();
     }

+ 63 - 42
src/Events/Select.php

@@ -14,6 +14,7 @@
 
 namespace Workerman\Events;
 
+use SplPriorityQueue;
 use Throwable;
 
 /**
@@ -25,62 +26,62 @@ class Select implements EventInterface
      * Running.
      * @var bool
      */
-    protected $running = true;
+    protected bool $running = true;
 
     /**
      * All listeners for read/write event.
      *
      * @var array
      */
-    protected $readEvents = [];
+    protected array $readEvents = [];
 
     /**
      * All listeners for read/write event.
      *
      * @var array
      */
-    protected $writeEvents = [];
+    protected array $writeEvents = [];
 
     /**
      * @var array
      */
-    protected $exceptEvents = [];
+    protected array $exceptEvents = [];
 
     /**
      * Event listeners of signal.
      *
      * @var array
      */
-    protected $signalEvents = [];
+    protected array $signalEvents = [];
 
     /**
      * Fds waiting for read event.
      *
      * @var array
      */
-    protected $readFds = [];
+    protected array $readFds = [];
 
     /**
      * Fds waiting for write event.
      *
      * @var array
      */
-    protected $writeFds = [];
+    protected array $writeFds = [];
 
     /**
      * Fds waiting for except event.
      *
      * @var array
      */
-    protected $exceptFds = [];
+    protected array $exceptFds = [];
 
     /**
      * Timer scheduler.
      * {['data':timer_id, 'priority':run_timestamp], ..}
      *
-     * @var \SplPriorityQueue
+     * @var SplPriorityQueue
      */
-    protected $scheduler = null;
+    protected SplPriorityQueue $scheduler;
 
     /**
      * All timer event listeners.
@@ -88,26 +89,26 @@ class Select implements EventInterface
      *
      * @var array
      */
-    protected $eventTimer = [];
+    protected array $eventTimer = [];
 
     /**
      * Timer id.
      *
      * @var int
      */
-    protected $timerId = 1;
+    protected int $timerId = 1;
 
     /**
      * Select timeout.
      *
      * @var int
      */
-    protected $selectTimeout = 100000000;
+    protected int $selectTimeout = 100000000;
 
     /**
-     * @var Closure || null
+     * @var ?callable
      */
-    protected $errorHandler;
+    protected $errorHandler = null;
 
     /**
      * Construct.
@@ -115,19 +116,19 @@ class Select implements EventInterface
     public function __construct()
     {
         // Init SplPriorityQueue.
-        $this->scheduler = new \SplPriorityQueue();
-        $this->scheduler->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
+        $this->scheduler = new SplPriorityQueue();
+        $this->scheduler->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
     }
 
     /**
      * {@inheritdoc}
      */
-    public function delay(float $delay, $func, $args = [])
+    public function delay(float $delay, callable $func, array $args = []): int
     {
         $timerId = $this->timerId++;
         $runTime = \microtime(true) + $delay;
         $this->scheduler->insert($timerId, -$runTime);
-        $this->eventTimer[$timerId] = [$func, (array)$args];
+        $this->eventTimer[$timerId] = [$func, $args];
         $selectTimeout = ($runTime - \microtime(true)) * 1000000;
         $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
         if ($this->selectTimeout > $selectTimeout) {
@@ -139,12 +140,12 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function repeat(float $delay, $func, $args = [])
+    public function repeat(float $interval, callable $func, array $args = []): int
     {
         $timerId = $this->timerId++;
-        $runTime = \microtime(true) + $delay;
+        $runTime = \microtime(true) + $interval;
         $this->scheduler->insert($timerId, -$runTime);
-        $this->eventTimer[$timerId] = [$func, (array)$args, $delay];
+        $this->eventTimer[$timerId] = [$func, $args, $interval];
         $selectTimeout = ($runTime - \microtime(true)) * 1000000;
         $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
         if ($this->selectTimeout > $selectTimeout) {
@@ -156,7 +157,7 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offDelay($timerId)
+    public function offDelay(int $timerId): bool
     {
         if (isset($this->eventTimer[$timerId])) {
             unset($this->eventTimer[$timerId]);
@@ -168,7 +169,7 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offRepeat($timerId)
+    public function offRepeat(int $timerId): bool
     {
         return $this->offDelay($timerId);
     }
@@ -176,7 +177,7 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function onReadable($stream, $func)
+    public function onReadable($stream, callable $func)
     {
         $count = \count($this->readFds);
         if ($count >= 1024) {
@@ -192,16 +193,20 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offReadable($stream)
+    public function offReadable($stream): bool
     {
         $fdKey = (int)$stream;
-        unset($this->readEvents[$fdKey], $this->readFds[$fdKey]);
+        if (isset($this->readEvents[$fdKey])) {
+            unset($this->readEvents[$fdKey], $this->readFds[$fdKey]);
+            return true;
+        }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onWritable($stream, $func)
+    public function onWritable($stream, callable $func)
     {
         $count = \count($this->writeFds);
         if ($count >= 1024) {
@@ -217,10 +222,14 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offWritable($stream)
+    public function offWritable($stream): bool
     {
         $fdKey = (int)$stream;
-        unset($this->writeEvents[$fdKey], $this->writeFds[$fdKey]);
+        if (isset($this->writeEvents[$fdKey])) {
+            unset($this->writeEvents[$fdKey], $this->writeFds[$fdKey]);
+            return true;
+        }
+        return false;
     }
 
     /**
@@ -236,19 +245,23 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offExcept($stream)
+    public function offExcept($stream): bool
     {
         $fdKey = (int)$stream;
-        unset($this->exceptEvents[$fdKey], $this->exceptFds[$fdKey]);
+        if (isset($this->exceptEvents[$fdKey])) {
+            unset($this->exceptEvents[$fdKey], $this->exceptFds[$fdKey]);
+            return true;
+        }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onSignal($signal, $func)
+    public function onSignal(int $signal, callable $func)
     {
         if (\DIRECTORY_SEPARATOR !== '/') {
-            return null;
+            return;
         }
         $this->signalEvents[$signal] = $func;
         \pcntl_signal($signal, [$this, 'signalHandler']);
@@ -257,10 +270,17 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offSignal($signal)
+    public function offSignal(int $signal): bool
     {
-        unset($this->signalEvents[$signal]);
+        if (\DIRECTORY_SEPARATOR !== '/') {
+            return false;
+        }
         \pcntl_signal($signal, SIG_IGN);
+        if (isset($this->signalEvents[$signal])) {
+            unset($this->signalEvents[$signal]);
+            return true;
+        }
+        return false;
     }
 
     /**
@@ -268,7 +288,7 @@ class Select implements EventInterface
      *
      * @param int $signal
      */
-    public function signalHandler($signal)
+    public function signalHandler(int $signal)
     {
         $this->signalEvents[$signal]($signal);
     }
@@ -277,6 +297,7 @@ class Select implements EventInterface
      * Tick for timer.
      *
      * @return void
+     * @throws Throwable
      */
     protected function tick()
     {
@@ -330,8 +351,8 @@ class Select implements EventInterface
      */
     public function deleteAllTimer()
     {
-        $this->scheduler = new \SplPriorityQueue();
-        $this->scheduler->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
+        $this->scheduler = new SplPriorityQueue();
+        $this->scheduler->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
         $this->eventTimer = [];
     }
 
@@ -403,7 +424,7 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getTimerCount()
+    public function getTimerCount(): int
     {
         return \count($this->eventTimer);
     }
@@ -411,7 +432,7 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function setErrorHandler($errorHandler)
+    public function setErrorHandler(callable $errorHandler)
     {
         $this->errorHandler = $errorHandler;
     }
@@ -419,7 +440,7 @@ class Select implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getErrorHandler()
+    public function getErrorHandler(): ?callable
     {
         return $this->errorHandler;
     }

+ 28 - 34
src/Events/Swoole.php

@@ -24,29 +24,24 @@ class Swoole implements EventInterface
      * All listeners for read timer
      * @var array
      */
-    protected $eventTimer = [];
+    protected array $eventTimer = [];
 
     /**
      * All listeners for read event.
      * @var array
      */
-    protected $readEvents = [];
+    protected array $readEvents = [];
 
     /**
      * All listeners for write event.
      * @var array
      */
-    protected $writeEvents = [];
+    protected array $writeEvents = [];
 
     /**
-     * @var int
+     * @var ?callable
      */
-    protected $mapId = 0;
-
-    /**
-     * @var Closure || null
-     */
-    protected $errorHandler;
+    protected $errorHandler = null;
 
     /**
      * Construct
@@ -60,14 +55,14 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function delay(float $delay, $func, $args = [])
+    public function delay(float $delay, callable $func, array $args = []): int
     {
         $t = (int)($delay * 1000);
-        $t = $t < 1 ? 1 : $t;
+        $t = max($t, 1);
         $timerId = Timer::after($t, function () use ($func, $args, &$timerId) {
             unset($this->eventTimer[$timerId]);
             try {
-                $func(...(array)$args);
+                $func(...$args);
             } catch (Throwable $e) {
                 $this->error($e);
             }
@@ -79,7 +74,7 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offDelay($timerId)
+    public function offDelay(int $timerId): bool
     {
         if (isset($this->eventTimer[$timerId])) {
             $res = Timer::clear($timerId);
@@ -92,7 +87,7 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offRepeat($timerId)
+    public function offRepeat(int $timerId): bool
     {
         return $this->offDelay($timerId);
     }
@@ -100,16 +95,13 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function repeat(float $interval, $func, $args = [])
+    public function repeat(float $interval, callable $func, array $args = []): int
     {
-        if ($this->mapId > \PHP_INT_MAX) {
-            $this->mapId = 0;
-        }
         $t = (int)($interval * 1000);
-        $t = $t < 1 ? 1 : $t;
+        $t = max($t, 1);
         $timerId = Timer::tick($t, function () use ($func, $args) {
             try {
-                $func(...(array)$args);
+                $func(...$args);
             } catch (Throwable $e) {
                 $this->error($e);
             }
@@ -121,7 +113,7 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function onReadable($stream, $func)
+    public function onReadable($stream, callable $func)
     {
         $fd = (int)$stream;
         if (!isset($this->readEvents[$fd]) && !isset($this->writeEvents[$fd])) {
@@ -139,24 +131,25 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offReadable($stream)
+    public function offReadable($stream): bool
     {
         $fd = (int)$stream;
         if (!isset($this->readEvents[$fd])) {
-            return;
+            return false;
         }
         unset($this->readEvents[$fd]);
         if (!isset($this->writeEvents[$fd])) {
             Event::del($stream);
-            return;
+            return true;
         }
         Event::set($stream, null, null, \SWOOLE_EVENT_WRITE);
+        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onWritable($stream, $func)
+    public function onWritable($stream, callable $func)
     {
         $fd = (int)$stream;
         if (!isset($this->readEvents[$fd]) && !isset($this->writeEvents[$fd])) {
@@ -174,24 +167,25 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offWritable($stream)
+    public function offWritable($stream): bool
     {
         $fd = (int)$stream;
         if (!isset($this->writeEvents[$fd])) {
-            return;
+            return false;
         }
         unset($this->writeEvents[$fd]);
         if (!isset($this->readEvents[$fd])) {
             Event::del($stream);
-            return;
+            return true;
         }
         Event::set($stream, null, null, \SWOOLE_EVENT_READ);
+        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onSignal($signal, $func)
+    public function onSignal(int $signal, callable $func)
     {
         return Process::signal($signal, $func);
     }
@@ -199,7 +193,7 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offSignal($signal)
+    public function offSignal(int $signal): bool
     {
         return Process::signal($signal, function () {});
     }
@@ -238,7 +232,7 @@ class Swoole implements EventInterface
      *
      * @return integer
      */
-    public function getTimerCount()
+    public function getTimerCount(): int
     {
         return \count($this->eventTimer);
     }
@@ -246,7 +240,7 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function setErrorHandler($errorHandler)
+    public function setErrorHandler(callable $errorHandler)
     {
         $this->errorHandler = $errorHandler;
     }
@@ -254,7 +248,7 @@ class Swoole implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getErrorHandler()
+    public function getErrorHandler(): ?callable
     {
         return $this->errorHandler;
     }

+ 31 - 25
src/Events/Swow.php

@@ -7,7 +7,6 @@ use Swow\Coroutine;
 use Swow\Signal;
 use Swow\SignalException;
 use Throwable;
-use function getmypid;
 use function max;
 use function msleep;
 use function stream_poll_one;
@@ -23,37 +22,37 @@ class Swow implements EventInterface
      * All listeners for read timer
      * @var array
      */
-    protected $eventTimer = [];
+    protected array $eventTimer = [];
 
     /**
      * All listeners for read event.
      * @var array<Coroutine>
      */
-    protected $readEvents = [];
+    protected array $readEvents = [];
 
     /**
      * All listeners for write event.
      * @var array<Coroutine>
      */
-    protected $writeEvents = [];
+    protected array $writeEvents = [];
 
     /**
      * All listeners for signal.
      * @var array<Coroutine>
      */
-    protected $signalListener = [];
+    protected array $signalListener = [];
 
     /**
-     * @var Closure || null
+     * @var ?callable
      */
-    protected $errorHandler;
+    protected $errorHandler = null;
 
     /**
      * Get timer count.
      *
      * @return integer
      */
-    public function getTimerCount()
+    public function getTimerCount(): int
     {
         return \count($this->eventTimer);
     }
@@ -61,7 +60,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function delay(float $delay, $func, $args = [])
+    public function delay(float $delay, callable $func, array $args = []): int
     {
         $t = (int) ($delay * 1000);
         $t = max($t, 1);
@@ -83,7 +82,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function repeat(float $interval, $func, $args = [])
+    public function repeat(float $interval, callable $func, array $args = []): int
     {
         $t = (int) ($interval * 1000);
         $t = max($t, 1);
@@ -106,7 +105,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offDelay($timerId)
+    public function offDelay(int $timerId): bool
     {
         if (isset($this->eventTimer[$timerId])) {
             try {
@@ -122,7 +121,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function offRepeat($timerId)
+    public function offRepeat(int $timerId): bool
     {
         return $this->offDelay($timerId);
     }
@@ -140,7 +139,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function onReadable($stream, $func)
+    public function onReadable($stream, callable $func)
     {
         $fd = (int) $stream;
         if (isset($this->readEvents[$fd])) {
@@ -170,22 +169,26 @@ class Swow implements EventInterface
                 $this->offReadable($stream);
             }
         });
-        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offReadable($stream)
+    public function offReadable($stream): bool
     {
         // 在当前协程执行 $coroutine->kill() 会导致不可预知问题,所以没有使用$coroutine->kill()
-        unset($this->readEvents[(int) $stream]);
+        $fd = (int) $stream;
+        if (isset($this->readEvents[$fd])) {
+            unset($this->readEvents[$fd]);
+            return true;
+        }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onWritable($stream, $func)
+    public function onWritable($stream, callable $func)
     {
         $fd = (int) $stream;
         if (isset($this->writeEvents[$fd])) {
@@ -211,21 +214,25 @@ class Swow implements EventInterface
                 $this->offWritable($stream);
             }
         });
-        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offWritable($stream)
+    public function offWritable($stream): bool
     {
-        unset($this->writeEvents[(int) $stream]);
+        $fd = (int) $stream;
+        if (isset($this->writeEvents[$fd])) {
+            unset($this->writeEvents[$fd]);
+            return true;
+        }
+        return false;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function onSignal($signal, $func)
+    public function onSignal(int $signal, callable $func)
     {
         Coroutine::run(function () use ($signal, $func): void {
             $this->signalListener[$signal] = Coroutine::getCurrent();
@@ -240,13 +247,12 @@ class Swow implements EventInterface
                 } catch (SignalException) {}
             }
         });
-        return true;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function offSignal($signal)
+    public function offSignal(int $signal): bool
     {
         if (!isset($this->signalListener[$signal])) {
             return false;
@@ -276,7 +282,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function setErrorHandler($errorHandler)
+    public function setErrorHandler(callable $errorHandler)
     {
         $this->errorHandler = $errorHandler;
     }
@@ -284,7 +290,7 @@ class Swow implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function getErrorHandler()
+    public function getErrorHandler(): ?callable
     {
         return $this->errorHandler;
     }

+ 6 - 9
src/Protocols/Frame.php

@@ -14,8 +14,6 @@
 
 namespace Workerman\Protocols;
 
-use Workerman\Connection\TcpConnection;
-
 /**
  * Frame Protocol.
  */
@@ -25,10 +23,9 @@ class Frame
      * Check the integrity of the package.
      *
      * @param string $buffer
-     * @param TcpConnection $connection
      * @return int
      */
-    public static function input($buffer, TcpConnection $connection)
+    public static function input(string $buffer): int
     {
         if (\strlen($buffer) < 4) {
             return 0;
@@ -43,7 +40,7 @@ class Frame
      * @param string $buffer
      * @return string
      */
-    public static function decode($buffer)
+    public static function decode(string $buffer): string
     {
         return \substr($buffer, 4);
     }
@@ -51,12 +48,12 @@ class Frame
     /**
      * Encode.
      *
-     * @param string $buffer
+     * @param string $data
      * @return string
      */
-    public static function encode($buffer)
+    public static function encode(string $data): string
     {
-        $totalLength = 4 + \strlen($buffer);
-        return \pack('N', $totalLength) . $buffer;
+        $totalLength = 4 + \strlen($data);
+        return \pack('N', $totalLength) . $data;
     }
 }

+ 35 - 32
src/Protocols/Http.php

@@ -14,6 +14,7 @@
 
 namespace Workerman\Protocols;
 
+use Throwable;
 use Workerman\Connection\TcpConnection;
 use Workerman\Protocols\Http\Request;
 use Workerman\Protocols\Http\Response;
@@ -29,21 +30,21 @@ class Http
      *
      * @var string
      */
-    protected static $requestClass = Request::class;
+    protected static string $requestClass = Request::class;
 
     /**
      * Upload tmp dir.
      *
      * @var string
      */
-    protected static $uploadTmpDir = '';
+    protected static string $uploadTmpDir = '';
 
     /**
      * Cache.
      *
      * @var bool.
      */
-    protected static $enableCache = true;
+    protected static bool $enableCache = true;
 
     /**
      * Get or set the request class name.
@@ -51,7 +52,7 @@ class Http
      * @param string|null $className
      * @return string
      */
-    public static function requestClass($className = null)
+    public static function requestClass(string $className = null): string
     {
         if ($className) {
             static::$requestClass = $className;
@@ -62,30 +63,31 @@ class Http
     /**
      * Enable or disable Cache.
      *
-     * @param mixed $value
+     * @param bool $value
      */
-    public static function enableCache($value)
+    public static function enableCache(bool $value)
     {
-        static::$enableCache = (bool)$value;
+        static::$enableCache = $value;
     }
 
     /**
      * Check the integrity of the package.
      *
-     * @param string $recvBuffer
+     * @param string $buffer
      * @param TcpConnection $connection
      * @return int
+     * @throws Throwable
      */
-    public static function input(string $recvBuffer, TcpConnection $connection)
+    public static function input(string $buffer, TcpConnection $connection): int
     {
         static $input = [];
-        if (!isset($recvBuffer[512]) && isset($input[$recvBuffer])) {
-            return $input[$recvBuffer];
+        if (!isset($buffer[512]) && isset($input[$buffer])) {
+            return $input[$buffer];
         }
-        $crlfPos = \strpos($recvBuffer, "\r\n\r\n");
+        $crlfPos = \strpos($buffer, "\r\n\r\n");
         if (false === $crlfPos) {
             // Judge whether the package length exceeds the limit.
-            if (\strlen($recvBuffer) >= 16384) {
+            if (\strlen($buffer) >= 16384) {
                 $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
                 return 0;
             }
@@ -93,14 +95,14 @@ class Http
         }
 
         $length = $crlfPos + 4;
-        $firstLine = \explode(" ", \strstr($recvBuffer, "\r\n", true), 3);
+        $firstLine = \explode(" ", \strstr($buffer, "\r\n", true), 3);
 
         if (!\in_array($firstLine[0], ['GET', 'POST', 'OPTIONS', 'HEAD', 'DELETE', 'PUT', 'PATCH'])) {
             $connection->close("HTTP/1.1 400 Bad Request\r\n\r\n", true);
             return 0;
         }
 
-        $header = \substr($recvBuffer, 0, $crlfPos);
+        $header = \substr($buffer, 0, $crlfPos);
         $hostHeaderPosition = \strpos($header, "\r\nHost: ");
 
         if (false === $hostHeaderPosition && $firstLine[2] === "HTTP/1.1") {
@@ -129,8 +131,8 @@ class Http
             }
         }
 
-        if (!isset($recvBuffer[512])) {
-            $input[$recvBuffer] = $length;
+        if (!isset($buffer[512])) {
+            $input[$buffer] = $length;
             if (\count($input) > 512) {
                 unset($input[key($input)]);
             }
@@ -142,26 +144,26 @@ class Http
     /**
      * Http decode.
      *
-     * @param string $recvBuffer
+     * @param string $buffer
      * @param TcpConnection $connection
-     * @return \Workerman\Protocols\Http\Request
+     * @return Request
      */
-    public static function decode($recvBuffer, TcpConnection $connection)
+    public static function decode(string $buffer, TcpConnection $connection): Request
     {
         static $requests = [];
-        $cacheable = static::$enableCache && !isset($recvBuffer[512]);
-        if (true === $cacheable && isset($requests[$recvBuffer])) {
-            $request = clone $requests[$recvBuffer];
+        $cacheable = static::$enableCache && !isset($buffer[512]);
+        if (true === $cacheable && isset($requests[$buffer])) {
+            $request = clone $requests[$buffer];
             $request->connection = $connection;
             $connection->request = $request;
             $request->properties = [];
             return $request;
         }
-        $request = new static::$requestClass($recvBuffer);
+        $request = new static::$requestClass($buffer);
         $request->connection = $connection;
         $connection->request = $request;
         if (true === $cacheable) {
-            $requests[$recvBuffer] = $request;
+            $requests[$buffer] = $request;
             if (\count($requests) > 512) {
                 unset($requests[\key($requests)]);
             }
@@ -175,13 +177,13 @@ class Http
      * @param string|Response $response
      * @param TcpConnection $connection
      * @return string
+     * @throws Throwable
      */
-    public static function encode($response, TcpConnection $connection)
+    public static function encode(mixed $response, TcpConnection $connection): string
     {
         if (isset($connection->request)) {
-            $connection->request->session = null;
-            $connection->request->connection = null;
-            $connection->request = null;
+            $request = $connection->request;
+            $request->session = $request->connection = $connection->request = null;
         }
         if (!\is_object($response)) {
             $extHeader = '';
@@ -246,7 +248,7 @@ class Http
      * @param int $offset
      * @param int $length
      */
-    protected static function sendStream(TcpConnection $connection, $handler, $offset = 0, $length = 0)
+    protected static function sendStream(TcpConnection $connection, $handler, int $offset = 0, int $length = 0)
     {
         $connection->context->bufferFull = false;
         $connection->context->streamSending = true;
@@ -297,9 +299,10 @@ class Http
     /**
      * Set or get uploadTmpDir.
      *
-     * @return bool|string
+     * @param string|null $dir
+     * @return string
      */
-    public static function uploadTmpDir($dir = null)
+    public static function uploadTmpDir(string|null $dir = null): string
     {
         if (null !== $dir) {
             static::$uploadTmpDir = $dir;

+ 3 - 2
src/Protocols/Http/Chunk.php

@@ -26,13 +26,14 @@ class Chunk
      *
      * @var string
      */
-    protected $buffer = null;
+    protected string $buffer;
 
     /**
      * Chunk constructor.
+     *
      * @param string $buffer
      */
-    public function __construct($buffer)
+    public function __construct(string $buffer)
     {
         $this->buffer = $buffer;
     }

+ 63 - 57
src/Protocols/Http/Request.php

@@ -14,6 +14,8 @@
 
 namespace Workerman\Protocols\Http;
 
+use Exception;
+use RuntimeException;
 use Workerman\Connection\TcpConnection;
 use Workerman\Protocols\Http;
 use Workerman\Worker;
@@ -27,68 +29,68 @@ class Request
     /**
      * Connection.
      *
-     * @var TcpConnection
+     * @var ?TcpConnection
      */
-    public $connection = null;
+    public ?TcpConnection $connection = null;
 
     /**
      * Session instance.
      *
-     * @var Session
+     * @var ?Session
      */
-    public $session = null;
+    public ?Session $session = null;
 
     /**
      * @var int
      */
-    public static $maxFileUploads = 1024;
+    public static int $maxFileUploads = 1024;
 
     /**
      * Properties.
      *
      * @var array
      */
-    public $properties = [];
+    public array $properties = [];
 
     /**
      * Http buffer.
      *
      * @var string
      */
-    protected $buffer = null;
+    protected string $buffer;
 
     /**
      * Request data.
      *
      * @var array
      */
-    protected $data = null;
+    protected array $data = [];
 
     /**
      * Enable cache.
      *
      * @var bool
      */
-    protected static $enableCache = true;
+    protected static bool $enableCache = true;
 
     /**
      * Request constructor.
      *
      * @param string $buffer
      */
-    public function __construct($buffer)
+    public function __construct(string $buffer)
     {
         $this->buffer = $buffer;
     }
 
     /**
-     * $GET.
+     * Get query.
      *
      * @param string|null $name
      * @param mixed|null $default
-     * @return mixed|null
+     * @return string|null|array
      */
-    public function get($name = null, $default = null)
+    public function get(string $name = null, mixed $default = null): array|string|null
     {
         if (!isset($this->data['get'])) {
             $this->parseGet();
@@ -100,13 +102,13 @@ class Request
     }
 
     /**
-     * $POST.
+     * Get post.
      *
      * @param string|null $name
      * @param mixed|null $default
-     * @return mixed|null
+     * @return string|null|array
      */
-    public function post($name = null, $default = null)
+    public function post(string $name = null, mixed $default = null): string|null|array
     {
         if (!isset($this->data['post'])) {
             $this->parsePost();
@@ -122,9 +124,9 @@ class Request
      *
      * @param string|null $name
      * @param mixed|null $default
-     * @return array|string|null
+     * @return string|null
      */
-    public function header($name = null, $default = null)
+    public function header(string $name = null, mixed $default = null): ?string
     {
         if (!isset($this->data['headers'])) {
             $this->parseHeaders();
@@ -141,9 +143,9 @@ class Request
      *
      * @param string|null $name
      * @param mixed|null $default
-     * @return array|string|null
+     * @return string|null|array
      */
-    public function cookie($name = null, $default = null)
+    public function cookie(string $name = null, mixed $default = null): array|string|null
     {
         if (!isset($this->data['cookie'])) {
             $this->data['cookie'] = [];
@@ -161,7 +163,7 @@ class Request
      * @param string|null $name
      * @return array|null
      */
-    public function file($name = null)
+    public function file(string $name = null)
     {
         if (!isset($this->data['files'])) {
             $this->parsePost();
@@ -177,7 +179,7 @@ class Request
      *
      * @return string
      */
-    public function method()
+    public function method(): string
     {
         if (!isset($this->data['method'])) {
             $this->parseHeadFirstLine();
@@ -190,7 +192,7 @@ class Request
      *
      * @return string
      */
-    public function protocolVersion()
+    public function protocolVersion(): string
     {
         if (!isset($this->data['protocolVersion'])) {
             $this->parseProtocolVersion();
@@ -202,9 +204,9 @@ class Request
      * Get host.
      *
      * @param bool $withoutPort
-     * @return string
+     * @return string|null
      */
-    public function host($withoutPort = false)
+    public function host(bool $withoutPort = false): ?string
     {
         $host = $this->header('host');
         if ($host && $withoutPort && $pos = \strpos($host, ':')) {
@@ -216,9 +218,9 @@ class Request
     /**
      * Get uri.
      *
-     * @return mixed
+     * @return string
      */
-    public function uri()
+    public function uri(): string
     {
         if (!isset($this->data['uri'])) {
             $this->parseHeadFirstLine();
@@ -229,9 +231,9 @@ class Request
     /**
      * Get path.
      *
-     * @return mixed
+     * @return string
      */
-    public function path()
+    public function path(): string
     {
         if (!isset($this->data['path'])) {
             $this->data['path'] = (string)\parse_url($this->uri(), PHP_URL_PATH);
@@ -242,9 +244,9 @@ class Request
     /**
      * Get query string.
      *
-     * @return mixed
+     * @return string
      */
-    public function queryString()
+    public function queryString(): string
     {
         if (!isset($this->data['query_string'])) {
             $this->data['query_string'] = (string)\parse_url($this->uri(), PHP_URL_QUERY);
@@ -255,16 +257,12 @@ class Request
     /**
      * Get session.
      *
-     * @return bool|Session
+     * @return Session
      */
-    public function session()
+    public function session(): Session
     {
         if ($this->session === null) {
-            $sessionId = $this->sessionId();
-            if ($sessionId === false) {
-                return false;
-            }
-            $this->session = new Session($sessionId);
+            $this->session = new Session($this->sessionId());
         }
         return $this->session;
     }
@@ -272,10 +270,11 @@ class Request
     /**
      * Get/Set session id.
      *
-     * @param $sessionId
+     * @param null $sessionId
      * @return string
+     * @throws Exception
      */
-    public function sessionId($sessionId = null)
+    public function sessionId($sessionId = null): string
     {
         if ($sessionId) {
             unset($this->sid);
@@ -284,9 +283,8 @@ class Request
             $sessionName = Session::$name;
             $sid = $sessionId ? '' : $this->cookie($sessionName);
             if ($sid === '' || $sid === null) {
-                if ($this->connection === null) {
-                    Worker::safeEcho('Request->session() fail, header already send');
-                    return false;
+                if (!$this->connection) {
+                    throw new RuntimeException('Request->session() fail, header already send');
                 }
                 $sid = $sessionId ?: static::createSessionId();
                 $cookieParams = Session::getCookieParams();
@@ -298,11 +296,13 @@ class Request
     }
 
     /**
-     * Session regenerate id
+     * Session regenerate id.
+     *
      * @param bool $deleteOldSession
-     * @return void
+     * @return string
+     * @throws Exception
      */
-    public function sessionRegenerateId($deleteOldSession = false)
+    public function sessionRegenerateId(bool $deleteOldSession = false): string
     {
         $session = $this->session();
         $sessionData = $session->all();
@@ -315,6 +315,7 @@ class Request
         $cookieParams = Session::getCookieParams();
         $sessionName = Session::$name;
         $this->setSidCookie($sessionName, $newSid, $cookieParams);
+        return $newSid;
     }
 
     /**
@@ -322,7 +323,7 @@ class Request
      *
      * @return string
      */
-    public function rawHead()
+    public function rawHead(): string
     {
         if (!isset($this->data['head'])) {
             $this->data['head'] = \strstr($this->buffer, "\r\n\r\n", true);
@@ -335,7 +336,7 @@ class Request
      *
      * @return string
      */
-    public function rawBody()
+    public function rawBody(): string
     {
         return \substr($this->buffer, \strpos($this->buffer, "\r\n\r\n") + 4);
     }
@@ -345,7 +346,7 @@ class Request
      *
      * @return string
      */
-    public function rawBuffer()
+    public function rawBuffer(): string
     {
         return $this->buffer;
     }
@@ -353,11 +354,11 @@ class Request
     /**
      * Enable or disable cache.
      *
-     * @param mixed $value
+     * @param bool $value
      */
-    public static function enableCache($value)
+    public static function enableCache(bool $value)
     {
-        static::$enableCache = (bool)$value;
+        static::$enableCache = $value;
     }
 
     /**
@@ -382,7 +383,7 @@ class Request
     {
         $firstLine = \strstr($this->buffer, "\r\n", true);
         $protocoVersion = substr(\strstr($firstLine, 'HTTP/'), 5);
-        $this->data['protocolVersion'] = $protocoVersion ? $protocoVersion : '1.0';
+        $this->data['protocolVersion'] = $protocoVersion ?: '1.0';
     }
 
     /**
@@ -407,7 +408,7 @@ class Request
         }
         $headData = \explode("\r\n", $headBuffer);
         foreach ($headData as $content) {
-            if (false !== \strpos($content, ':')) {
+            if (str_contains($content, ':')) {
                 list($key, $value) = \explode(':', $content, 2);
                 $key = \strtolower($key);
                 $value = \ltrim($value);
@@ -525,11 +526,16 @@ class Request
     }
 
     /**
+     * Parse upload file.
+     *
      * @param $boundary
      * @param $sectionStartOffset
+     * @param $postEncodeString
+     * @param $filesEncodeStr
+     * @param $files
      * @return int
      */
-    protected function parseUploadFile($boundary, $sectionStartOffset, &$postEncodeString, &$filesEncodeStr, &$files)
+    protected function parseUploadFile($boundary, $sectionStartOffset, &$postEncodeString, &$filesEncodeStr, &$files): int
     {
         $file = [];
         $boundary = "\r\n$boundary";
@@ -590,7 +596,6 @@ class Request
                         }
                         return $sectionEndOffset + \strlen($boundary) + 2;
                     }
-                    break;
                 case "content-type":
                     $file['type'] = \trim($value);
                     break;
@@ -609,8 +614,9 @@ class Request
      * Create session id.
      *
      * @return string
+     * @throws Exception
      */
-    public static function createSessionId()
+    public static function createSessionId(): string
     {
         return \bin2hex(\pack('d', \microtime(true)) . random_bytes(8));
     }

+ 34 - 35
src/Protocols/Http/Response.php

@@ -25,48 +25,48 @@ class Response
      *
      * @var array
      */
-    protected $headers = null;
+    protected array $headers = [];
 
     /**
      * Http status.
      *
      * @var int
      */
-    protected $status = null;
+    protected int $status;
 
     /**
      * Http reason.
      *
-     * @var string
+     * @var ?string
      */
-    protected $reason = null;
+    protected ?string $reason = null;
 
     /**
      * Http version.
      *
      * @var string
      */
-    protected $version = '1.1';
+    protected string $version = '1.1';
 
     /**
      * Http body.
      *
      * @var string
      */
-    protected $body = null;
+    protected string $body = '';
 
     /**
      * Send file info
      *
-     * @var array
+     * @var ?array
      */
-    public $file = null;
+    public ?array $file = null;
 
     /**
      * Mine type map.
      * @var array
      */
-    protected static $mimeTypeMap = null;
+    protected static array $mimeTypeMap = [];
 
     /**
      * Phrases.
@@ -163,14 +163,14 @@ class Response
      * @param string $body
      */
     public function __construct(
-        $status = 200,
-        $headers = [],
-        $body = ''
+        int   $status = 200,
+        array $headers = [],
+        string $body = ''
     )
     {
         $this->status = $status;
         $this->headers = $headers;
-        $this->body = (string)$body;
+        $this->body = $body;
     }
 
     /**
@@ -180,7 +180,7 @@ class Response
      * @param string $value
      * @return $this
      */
-    public function header($name, $value)
+    public function header(string $name, string $value): static
     {
         $this->headers[$name] = $value;
         return $this;
@@ -193,7 +193,7 @@ class Response
      * @param string $value
      * @return Response
      */
-    public function withHeader($name, $value)
+    public function withHeader(string $name, string $value): static
     {
         return $this->header($name, $value);
     }
@@ -204,7 +204,7 @@ class Response
      * @param array $headers
      * @return $this
      */
-    public function withHeaders($headers)
+    public function withHeaders(array $headers): static
     {
         $this->headers = \array_merge_recursive($this->headers, $headers);
         return $this;
@@ -216,7 +216,7 @@ class Response
      * @param string $name
      * @return $this
      */
-    public function withoutHeader($name)
+    public function withoutHeader(string $name): static
     {
         unset($this->headers[$name]);
         return $this;
@@ -228,9 +228,8 @@ class Response
      * @param string $name
      * @return null|array|string
      */
-    public function getHeader($name)
+    public function getHeader(string $name): array|string|null
     {
-
         return $this->headers[$name] ?? null;
     }
 
@@ -239,7 +238,7 @@ class Response
      *
      * @return array
      */
-    public function getHeaders()
+    public function getHeaders(): array
     {
         return $this->headers;
     }
@@ -251,7 +250,7 @@ class Response
      * @param string|null $reasonPhrase
      * @return $this
      */
-    public function withStatus($code, $reasonPhrase = null)
+    public function withStatus(int $code, string $reasonPhrase = null): static
     {
         $this->status = $code;
         $this->reason = $reasonPhrase;
@@ -263,7 +262,7 @@ class Response
      *
      * @return int
      */
-    public function getStatusCode()
+    public function getStatusCode(): int
     {
         return $this->status;
     }
@@ -271,9 +270,9 @@ class Response
     /**
      * Get reason phrase.
      *
-     * @return string
+     * @return ?string
      */
-    public function getReasonPhrase()
+    public function getReasonPhrase(): ?string
     {
         return $this->reason;
     }
@@ -281,10 +280,10 @@ class Response
     /**
      * Set protocol version.
      *
-     * @param int $version
+     * @param string $version
      * @return $this
      */
-    public function withProtocolVersion($version)
+    public function withProtocolVersion(string $version): static
     {
         $this->version = $version;
         return $this;
@@ -296,9 +295,9 @@ class Response
      * @param string $body
      * @return $this
      */
-    public function withBody($body)
+    public function withBody(string $body): static
     {
-        $this->body = (string)$body;
+        $this->body = $body;
         return $this;
     }
 
@@ -307,7 +306,7 @@ class Response
      *
      * @return string
      */
-    public function rawBody()
+    public function rawBody(): string
     {
         return $this->body;
     }
@@ -320,7 +319,7 @@ class Response
      * @param int $length
      * @return $this
      */
-    public function withFile($file, $offset = 0, $length = 0)
+    public function withFile(string $file, int $offset = 0, int $length = 0): static
     {
         if (!\is_file($file)) {
             return $this->withStatus(404)->withBody('<h3>404 Not Found</h3>');
@@ -332,9 +331,9 @@ class Response
     /**
      * Set cookie.
      *
-     * @param $name
+     * @param string $name
      * @param string $value
-     * @param int $maxAge
+     * @param int|null $maxAge
      * @param string $path
      * @param string $domain
      * @param bool $secure
@@ -342,7 +341,7 @@ class Response
      * @param bool $sameSite
      * @return $this
      */
-    public function cookie($name, $value = '', $maxAge = null, $path = '', $domain = '', $secure = false, $httpOnly = false, $sameSite  = false)
+    public function cookie(string $name, string $value = '', int $maxAge = null, string $path = '', string $domain = '', bool $secure = false, bool $httpOnly = false, bool $sameSite  = false): static
     {
         $this->headers['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
             . (empty($domain) ? '' : '; Domain=' . $domain)
@@ -360,7 +359,7 @@ class Response
      * @param array $fileInfo
      * @return string
      */
-    protected function createHeadForFile($fileInfo)
+    protected function createHeadForFile(array $fileInfo): string
     {
         $file = $fileInfo['file'];
         $reason = $this->reason ?: self::PHRASES[$this->status];
@@ -414,7 +413,7 @@ class Response
      */
     public function __toString()
     {
-        if (isset($this->file)) {
+        if ($this->file) {
             return $this->createHeadForFile($this->file);
         }
 

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

@@ -24,7 +24,7 @@ class ServerSentEvents
      * Data.
      * @var array
      */
-    protected $data = null;
+    protected array $data;
 
     /**
      * ServerSentEvents constructor.

+ 41 - 47
src/Protocols/Http/Session.php

@@ -14,6 +14,8 @@
 
 namespace Workerman\Protocols\Http;
 
+use Exception;
+use RuntimeException;
 use Workerman\Protocols\Http\Session\FileSessionHandler;
 use Workerman\Protocols\Http\Session\SessionHandlerInterface;
 
@@ -28,119 +30,119 @@ class Session
      *
      * @var string
      */
-    protected static $handlerClass = FileSessionHandler::class;
+    protected static string $handlerClass = FileSessionHandler::class;
 
     /**
      * Parameters of __constructor for session handler class.
      *
-     * @var null
+     * @var mixed
      */
-    protected static $handlerConfig = null;
+    protected static mixed $handlerConfig = null;
 
     /**
      * Session name.
      *
      * @var string
      */
-    public static $name = 'PHPSID';
+    public static string $name = 'PHPSID';
 
     /**
      * Auto update timestamp.
      *
      * @var bool
      */
-    public static $autoUpdateTimestamp = false;
+    public static bool $autoUpdateTimestamp = false;
 
     /**
      * Session lifetime.
      *
      * @var int
      */
-    public static $lifetime = 1440;
+    public static int $lifetime = 1440;
 
     /**
      * Cookie lifetime.
      *
      * @var int
      */
-    public static $cookieLifetime = 1440;
+    public static int $cookieLifetime = 1440;
 
     /**
      * Session cookie path.
      *
      * @var string
      */
-    public static $cookiePath = '/';
+    public static string $cookiePath = '/';
 
     /**
      * Session cookie domain.
      *
      * @var string
      */
-    public static $domain = '';
+    public static string $domain = '';
 
     /**
      * HTTPS only cookies.
      *
      * @var bool
      */
-    public static $secure = false;
+    public static bool $secure = false;
 
     /**
      * HTTP access only.
      *
      * @var bool
      */
-    public static $httpOnly = true;
+    public static bool $httpOnly = true;
 
     /**
      * Same-site cookies.
      *
      * @var string
      */
-    public static $sameSite = '';
+    public static string $sameSite = '';
 
     /**
      * Gc probability.
      *
      * @var int[]
      */
-    public static $gcProbability = [1, 1000];
+    public static array $gcProbability = [1, 20000];
 
     /**
      * Session handler instance.
      *
-     * @var SessionHandlerInterface
+     * @var ?SessionHandlerInterface
      */
-    protected static $handler = null;
+    protected static ?SessionHandlerInterface $handler = null;
 
     /**
      * Session data.
      *
      * @var array
      */
-    protected $data = [];
+    protected mixed $data = [];
 
     /**
      * Session changed and need to save.
      *
      * @var bool
      */
-    protected $needSave = false;
+    protected bool $needSave = false;
 
     /**
      * Session id.
      *
-     * @var null
+     * @var string
      */
-    protected $sessionId = null;
+    protected string $sessionId;
 
     /**
      * Session constructor.
      *
      * @param string $sessionId
      */
-    public function __construct($sessionId)
+    public function __construct(string $sessionId)
     {
         static::checkSessionId($sessionId);
         if (static::$handler === null) {
@@ -157,7 +159,7 @@ class Session
      *
      * @return string
      */
-    public function getId()
+    public function getId(): string
     {
         return $this->sessionId;
     }
@@ -167,9 +169,9 @@ class Session
      *
      * @param string $name
      * @param mixed|null $default
-     * @return mixed|null
+     * @return mixed
      */
-    public function get($name, $default = null)
+    public function get(string $name, mixed $default = null): mixed
     {
         return $this->data[$name] ?? $default;
     }
@@ -180,7 +182,7 @@ class Session
      * @param string $name
      * @param mixed $value
      */
-    public function set($name, $value)
+    public function set(string $name, mixed $value)
     {
         $this->data[$name] = $value;
         $this->needSave = true;
@@ -191,7 +193,7 @@ class Session
      *
      * @param string $name
      */
-    public function delete($name)
+    public function delete(string $name)
     {
         unset($this->data[$name]);
         $this->needSave = true;
@@ -202,9 +204,9 @@ class Session
      *
      * @param string $name
      * @param mixed|null $default
-     * @return mixed|null
+     * @return mixed
      */
-    public function pull($name, $default = null)
+    public function pull(string $name, mixed $default = null): mixed
     {
         $value = $this->get($name, $default);
         $this->delete($name);
@@ -214,10 +216,10 @@ class Session
     /**
      * Store data in the session.
      *
-     * @param string|array $key
+     * @param array|string $key
      * @param mixed|null $value
      */
-    public function put($key, $value = null)
+    public function put(array|string $key, mixed $value = null)
     {
         if (!\is_array($key)) {
             $this->set($key, $value);
@@ -233,9 +235,9 @@ class Session
     /**
      * Remove a piece of data from the session.
      *
-     * @param string $name
+     * @param array|string $name
      */
-    public function forget($name)
+    public function forget(array|string $name)
     {
         if (\is_scalar($name)) {
             $this->delete($name);
@@ -254,7 +256,7 @@ class Session
      *
      * @return array
      */
-    public function all()
+    public function all(): array
     {
         return $this->data;
     }
@@ -276,7 +278,7 @@ class Session
      * @param string $name
      * @return bool
      */
-    public function has($name)
+    public function has(string $name): bool
     {
         return isset($this->data[$name]);
     }
@@ -287,7 +289,7 @@ class Session
      * @param string $name
      * @return bool
      */
-    public function exists($name)
+    public function exists(string $name): bool
     {
         return \array_key_exists($name, $this->data);
     }
@@ -316,7 +318,7 @@ class Session
      *
      * @return bool
      */
-    public function refresh()
+    public function refresh(): bool
     {
         return static::$handler->updateTimestamp($this->getId());
     }
@@ -351,7 +353,7 @@ class Session
      * @param mixed|null $config
      * @return string
      */
-    public static function handlerClass($className = null, $config = null)
+    public static function handlerClass(mixed $className = null, mixed $config = null): string
     {
         if ($className) {
             static::$handlerClass = $className;
@@ -367,7 +369,7 @@ class Session
      *
      * @return array
      */
-    public static function getCookieParams()
+    public static function getCookieParams(): array
     {
         return [
             'lifetime' => static::$cookieLifetime,
@@ -407,6 +409,7 @@ class Session
      * __destruct.
      *
      * @return void
+     * @throws Exception
      */
     public function __destruct()
     {
@@ -424,19 +427,10 @@ class Session
     protected static function checkSessionId($sessionId)
     {
         if (!\preg_match('/^[a-zA-Z0-9]+$/', $sessionId)) {
-            throw new SessionException("session_id $sessionId is invalid");
+            throw new RuntimeException("session_id $sessionId is invalid");
         }
     }
 }
 
-/**
- * Class SessionException
- * @package Workerman\Protocols\Http
- */
-class SessionException extends \RuntimeException
-{
-
-}
-
 // Init session.
 Session::init();

+ 15 - 14
src/Protocols/Http/Session/FileSessionHandler.php

@@ -27,14 +27,14 @@ class FileSessionHandler implements SessionHandlerInterface
      *
      * @var string
      */
-    protected static $sessionSavePath = null;
+    protected static string $sessionSavePath;
 
     /**
      * Session file prefix.
      *
      * @var string
      */
-    protected static $sessionFilePrefix = 'session_';
+    protected static string $sessionFilePrefix = 'session_';
 
     /**
      * Init.
@@ -42,7 +42,7 @@ class FileSessionHandler implements SessionHandlerInterface
     public static function init()
     {
         $savePath = @\session_save_path();
-        if (!$savePath || \strpos($savePath, 'tcp://') === 0) {
+        if (!$savePath || str_starts_with($savePath, 'tcp://')) {
             $savePath = \sys_get_temp_dir();
         }
         static::sessionSavePath($savePath);
@@ -52,7 +52,7 @@ class FileSessionHandler implements SessionHandlerInterface
      * FileSessionHandler constructor.
      * @param array $config
      */
-    public function __construct($config = [])
+    public function __construct(array $config = [])
     {
         if (isset($config['save_path'])) {
             static::sessionSavePath($config['save_path']);
@@ -62,7 +62,7 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function open($savePath, $name)
+    public function open(string $savePath, string $name): bool
     {
         return true;
     }
@@ -70,7 +70,7 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function read($sessionId)
+    public function read(string $sessionId): string
     {
         $sessionFile = static::sessionFile($sessionId);
         \clearstatcache();
@@ -88,7 +88,7 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function write($sessionId, $sessionData)
+    public function write(string $sessionId, string $sessionData): bool
     {
         $tempFile = static::$sessionSavePath . uniqid(bin2hex(random_bytes(8)), true);
         if (!\file_put_contents($tempFile, $sessionData)) {
@@ -108,7 +108,7 @@ class FileSessionHandler implements SessionHandlerInterface
      *
      * @return bool
      */
-    public function updateTimestamp($id, $data = "")
+    public function updateTimestamp(string $id, string $data = ""): bool
     {
         $sessionFile = static::sessionFile($id);
         if (!file_exists($sessionFile)) {
@@ -124,7 +124,7 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function close()
+    public function close(): bool
     {
         return true;
     }
@@ -132,7 +132,7 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function destroy($sessionId)
+    public function destroy(string $sessionId): bool
     {
         $sessionFile = static::sessionFile($sessionId);
         if (\is_file($sessionFile)) {
@@ -144,14 +144,15 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function gc($maxlifetime)
+    public function gc(int $maxLifetime): bool
     {
         $timeNow = \time();
         foreach (\glob(static::$sessionSavePath . static::$sessionFilePrefix . '*') as $file) {
-            if (\is_file($file) && $timeNow - \filemtime($file) > $maxlifetime) {
+            if (\is_file($file) && $timeNow - \filemtime($file) > $maxLifetime) {
                 \unlink($file);
             }
         }
+        return true;
     }
 
     /**
@@ -160,7 +161,7 @@ class FileSessionHandler implements SessionHandlerInterface
      * @param string $sessionId
      * @return string
      */
-    protected static function sessionFile($sessionId)
+    protected static function sessionFile(string $sessionId): string
     {
         return static::$sessionSavePath . static::$sessionFilePrefix . $sessionId;
     }
@@ -171,7 +172,7 @@ class FileSessionHandler implements SessionHandlerInterface
      * @param string $path
      * @return string
      */
-    public static function sessionSavePath($path)
+    public static function sessionSavePath(string $path): string
     {
         if ($path) {
             if ($path[\strlen($path) - 1] !== DIRECTORY_SEPARATOR) {

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

@@ -15,9 +15,14 @@
 namespace Workerman\Protocols\Http\Session;
 
 use Workerman\Protocols\Http\Session;
+use RedisClusterException;
 
 class RedisClusterSessionHandler extends RedisSessionHandler
 {
+    /**
+     * @param $config
+     * @throws RedisClusterException
+     */
     public function __construct($config)
     {
         $timeout = $config['timeout'] ?? 2;
@@ -38,7 +43,7 @@ class RedisClusterSessionHandler extends RedisSessionHandler
     /**
      * {@inheritdoc}
      */
-    public function read($sessionId)
+    public function read(string $sessionId): string
     {
         return $this->redis->get($sessionId);
     }

+ 17 - 14
src/Protocols/Http/Session/RedisSessionHandler.php

@@ -14,6 +14,8 @@
 
 namespace Workerman\Protocols\Http\Session;
 
+use Redis;
+use Throwable;
 use Workerman\Protocols\Http\Session;
 use Workerman\Timer;
 use RedisException;
@@ -26,14 +28,14 @@ class RedisSessionHandler implements SessionHandlerInterface
 {
 
     /**
-     * @var \Redis
+     * @var Redis
      */
-    protected $redis;
+    protected Redis $redis;
 
     /**
      * @var array
      */
-    protected $config;
+    protected array $config;
 
     /**
      * RedisSessionHandler constructor.
@@ -47,7 +49,7 @@ class RedisSessionHandler implements SessionHandlerInterface
      *  'ping'     => 55,
      * ]
      */
-    public function __construct($config)
+    public function __construct(array $config)
     {
         if (false === extension_loaded('redis')) {
             throw new \RuntimeException('Please install redis extension.');
@@ -70,7 +72,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     {
         $config = $this->config;
 
-        $this->redis = new \Redis();
+        $this->redis = new Redis();
         if (false === $this->redis->connect($config['host'], $config['port'], $config['timeout'])) {
             throw new \RuntimeException("Redis connect {$config['host']}:{$config['port']} fail.");
         }
@@ -83,25 +85,26 @@ class RedisSessionHandler implements SessionHandlerInterface
         if (empty($config['prefix'])) {
             $config['prefix'] = 'redis_session_';
         }
-        $this->redis->setOption(\Redis::OPT_PREFIX, $config['prefix']);
+        $this->redis->setOption(Redis::OPT_PREFIX, $config['prefix']);
     }
 
     /**
      * {@inheritdoc}
      */
-    public function open($savePath, $name)
+    public function open(string $savePath, string $name): bool
     {
         return true;
     }
 
     /**
      * {@inheritdoc}
+     * @throws RedisException
      */
-    public function read($sessionId)
+    public function read(string $sessionId): string
     {
         try {
             return $this->redis->get($sessionId);
-        } catch (RedisException $e) {
+        } catch (Throwable $e) {
             $msg = strtolower($e->getMessage());
             if ($msg === 'connection lost' || strpos($msg, 'went away')) {
                 $this->connect();
@@ -114,7 +117,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function write($sessionId, $sessionData)
+    public function write(string $sessionId, string $sessionData): bool
     {
         return true === $this->redis->setex($sessionId, Session::$lifetime, $sessionData);
     }
@@ -122,7 +125,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function updateTimestamp($id, $data = "")
+    public function updateTimestamp(string $id, string $data = ""): bool
     {
         return true === $this->redis->expire($id, Session::$lifetime);
     }
@@ -130,7 +133,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function destroy($sessionId)
+    public function destroy(string $sessionId): bool
     {
         $this->redis->del($sessionId);
         return true;
@@ -139,7 +142,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function close()
+    public function close(): bool
     {
         return true;
     }
@@ -147,7 +150,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function gc($maxlifetime)
+    public function gc(int $maxLifetime): bool
     {
         return true;
     }

+ 9 - 9
src/Protocols/Http/Session/SessionHandlerInterface.php

@@ -25,7 +25,7 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function close();
+    public function close(): bool;
 
     /**
      * Destroy a session
@@ -37,12 +37,12 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function destroy($sessionId);
+    public function destroy(string $sessionId): bool;
 
     /**
      * Cleanup old sessions
      * @link http://php.net/manual/en/sessionhandlerinterface.gc.php
-     * @param int $maxlifetime <p>
+     * @param int $maxLifetime <p>
      * Sessions that have not updated for
      * the last maxlifetime seconds will be removed.
      * </p>
@@ -52,7 +52,7 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function gc($maxlifetime);
+    public function gc(int $maxLifetime): bool;
 
     /**
      * Initialize session
@@ -65,7 +65,7 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function open($savePath, $name);
+    public function open(string $savePath, string $name): bool;
 
 
     /**
@@ -79,7 +79,7 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function read($sessionId);
+    public function read(string $sessionId): string;
 
     /**
      * Write session data
@@ -98,18 +98,18 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function write($sessionId, $sessionData);
+    public function write(string $sessionId, string $sessionData): bool;
 
     /**
      * Update sesstion modify time.
      *
      * @see https://www.php.net/manual/en/class.sessionupdatetimestamphandlerinterface.php
      *
-     * @param string $id Session id.
+     * @param string $sessionId
      * @param string $data Session Data.
      *
      * @return bool
      */
-    public function updateTimestamp($id, $data = "");
+    public function updateTimestamp(string $sessionId, string $data = ""): bool;
 
 }

+ 5 - 5
src/Protocols/ProtocolInterface.php

@@ -27,20 +27,20 @@ interface ProtocolInterface
      * If length is unknown please return 0 that means waiting for more data.
      * If the package has something wrong please return false the connection will be closed.
      *
-     * @param string $recvBuffer
+     * @param string $buffer
      * @param ConnectionInterface $connection
      * @return int|false
      */
-    public static function input($recvBuffer, ConnectionInterface $connection);
+    public static function input(string $buffer, ConnectionInterface $connection): bool|int;
 
     /**
      * Decode package and emit onMessage($message) callback, $message is the result that decode returned.
      *
-     * @param string $recvBuffer
+     * @param string $buffer
      * @param ConnectionInterface $connection
      * @return mixed
      */
-    public static function decode($recvBuffer, ConnectionInterface $connection);
+    public static function decode(string $buffer, ConnectionInterface $connection): mixed;
 
     /**
      * Encode package before sending to client.
@@ -49,5 +49,5 @@ interface ProtocolInterface
      * @param ConnectionInterface $connection
      * @return string
      */
-    public static function encode($data, ConnectionInterface $connection);
+    public static function encode(mixed $data, ConnectionInterface $connection): string;
 }

+ 3 - 3
src/Protocols/Text.php

@@ -28,7 +28,7 @@ class Text
      * @param ConnectionInterface $connection
      * @return int
      */
-    public static function input($buffer, ConnectionInterface $connection)
+    public static function input(string $buffer, ConnectionInterface $connection): int
     {
         // Judge whether the package length exceeds the limit.
         if (isset($connection->maxPackageSize) && \strlen($buffer) >= $connection->maxPackageSize) {
@@ -51,7 +51,7 @@ class Text
      * @param string $buffer
      * @return string
      */
-    public static function encode($buffer)
+    public static function encode(string $buffer): string
     {
         // Add "\n"
         return $buffer . "\n";
@@ -63,7 +63,7 @@ class Text
      * @param string $buffer
      * @return string
      */
-    public static function decode($buffer)
+    public static function decode(string $buffer): string
     {
         // Remove "\n"
         return \rtrim($buffer, "\r\n");

+ 21 - 28
src/Protocols/Websocket.php

@@ -14,6 +14,7 @@
 
 namespace Workerman\Protocols;
 
+use Throwable;
 use Workerman\Connection\ConnectionInterface;
 use Workerman\Connection\TcpConnection;
 use Workerman\Protocols\Http\Request;
@@ -22,7 +23,7 @@ use Workerman\Worker;
 /**
  * WebSocket protocol.
  */
-class Websocket implements \Workerman\Protocols\ProtocolInterface
+class Websocket
 {
     /**
      * Websocket blob type.
@@ -42,10 +43,11 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
      * Check the integrity of the package.
      *
      * @param string $buffer
-     * @param ConnectionInterface $connection
+     * @param TcpConnection $connection
      * @return int
+     * @throws Throwable
      */
-    public static function input($buffer, ConnectionInterface $connection)
+    public static function input(string $buffer, TcpConnection $connection): int
     {
         // Receive length.
         $recvLen = \strlen($buffer);
@@ -98,7 +100,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                     if ($closeCb) {
                         try {
                             $closeCb($connection);
-                        } catch (\Throwable $e) {
+                        } catch (Throwable $e) {
                             Worker::stopAll(250, $e);
                         }
                     } // Close connection.
@@ -152,7 +154,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                         if ($pingCb) {
                             try {
                                 $pingCb($connection, $pingData);
-                            } catch (\Throwable $e) {
+                            } catch (Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         } else {
@@ -175,7 +177,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                         if ($pongCb) {
                             try {
                                 $pongCb($connection, $pongData);
-                            } catch (\Throwable $e) {
+                            } catch (Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         }
@@ -216,14 +218,11 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
      * Websocket encode.
      *
      * @param string $buffer
-     * @param ConnectionInterface $connection
+     * @param TcpConnection $connection
      * @return string
      */
-    public static function encode($buffer, ConnectionInterface $connection)
+    public static function encode(string $buffer, TcpConnection $connection): string
     {
-        if (!is_scalar($buffer)) {
-            throw new \Exception("You can't send(" . \gettype($buffer) . ") to client, you need to convert it to a string. ");
-        }
         $len = \strlen($buffer);
         if (empty($connection->websocketType)) {
             $connection->websocketType = static::BINARY_TYPE_BLOB;
@@ -251,7 +250,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 if ($connection->onError) {
                     try {
                         ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package');
-                    } catch (\Throwable $e) {
+                    } catch (Throwable $e) {
                         Worker::stopAll(250, $e);
                     }
                 }
@@ -263,7 +262,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 if ($connection->onBufferFull) {
                     try {
                         ($connection->onBufferFull)($connection);
-                    } catch (\Throwable $e) {
+                    } catch (Throwable $e) {
                         Worker::stopAll(250, $e);
                     }
                 }
@@ -279,10 +278,10 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
      * Websocket decode.
      *
      * @param string $buffer
-     * @param ConnectionInterface $connection
+     * @param TcpConnection $connection
      * @return string
      */
-    public static function decode($buffer, ConnectionInterface $connection)
+    public static function decode(string $buffer, TcpConnection $connection): string
     {
         $firstByte = \ord($buffer[1]);
         $len = $firstByte & 127;
@@ -321,8 +320,9 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
      * @param string $buffer
      * @param TcpConnection $connection
      * @return int
+     * @throws Throwable
      */
-    public static function dealHandshake($buffer, ConnectionInterface $connection)
+    public static function dealHandshake(string $buffer, TcpConnection $connection): int
     {
         // HTTP protocol.
         if (0 === \strpos($buffer, 'GET')) {
@@ -365,7 +365,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             if ($onWebsocketConnect) {
                 try {
                     $onWebsocketConnect($connection, new Request($buffer));
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     Worker::stopAll(250, $e);
                 }
             }
@@ -377,19 +377,12 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
 
             $hasServerHeader = false;
 
-            if (isset($connection->headers)) {
-                if (\is_array($connection->headers)) {
-                    foreach ($connection->headers as $header) {
-                        if (\stripos($header, 'Server:') === 0) {
-                            $hasServerHeader = true;
-                        }
-                        $handshakeMessage .= "$header\r\n";
-                    }
-                } else {
-                    if (\stripos($connection->headers, 'Server:') !== false) {
+            if ($connection->headers) {
+                foreach ($connection->headers as $header) {
+                    if (\stripos($header, 'Server:') === 0) {
                         $hasServerHeader = true;
                     }
-                    $handshakeMessage .= "$connection->headers\r\n";
+                    $handshakeMessage .= "$header\r\n";
                 }
             }
             if (!$hasServerHeader) {

+ 23 - 19
src/Protocols/Ws.php

@@ -14,6 +14,7 @@
 
 namespace Workerman\Protocols;
 
+use Throwable;
 use Workerman\Worker;
 use Workerman\Timer;
 use Workerman\Connection\TcpConnection;
@@ -42,10 +43,11 @@ class Ws
      * Check the integrity of the package.
      *
      * @param string $buffer
-     * @param ConnectionInterface $connection
-     * @return int
+     * @param TcpConnection $connection
+     * @return int|false
+     * @throws Throwable
      */
-    public static function input($buffer, ConnectionInterface $connection)
+    public static function input(string $buffer, TcpConnection $connection): bool|int
     {
         if (empty($connection->context->handshakeStep)) {
             Worker::safeEcho("recv data before handshake. Buffer:" . \bin2hex($buffer) . "\n");
@@ -99,7 +101,7 @@ class Ws
                     if (isset($connection->onWebSocketClose)) {
                         try {
                             ($connection->onWebSocketClose)($connection);
-                        } catch (\Throwable $e) {
+                        } catch (Throwable $e) {
                             Worker::stopAll(250, $e);
                         }
                     } // Close connection.
@@ -147,7 +149,7 @@ class Ws
                         if (isset($connection->onWebSocketPing)) {
                             try {
                                 ($connection->onWebSocketPing)($connection, $pingData);
-                            } catch (\Throwable $e) {
+                            } catch (Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         } else {
@@ -170,7 +172,7 @@ class Ws
                         if (isset($connection->onWebSocketPong)) {
                             try {
                                 ($connection->onWebSocketPong)($connection, $pongData);
-                            } catch (\Throwable $e) {
+                            } catch (Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         }
@@ -209,16 +211,16 @@ class Ws
     /**
      * Websocket encode.
      *
-     * @param string $buffer
-     * @param ConnectionInterface $connection
+     * @param string $payload
+     * @param TcpConnection $connection
      * @return string
      */
-    public static function encode($payload, ConnectionInterface $connection)
+    public static function encode(string $payload, TcpConnection $connection): string
     {
         if (empty($connection->websocketType)) {
             $connection->websocketType = self::BINARY_TYPE_BLOB;
         }
-        $payload = (string)$payload;
+        $payload = $payload;
         if (empty($connection->context->handshakeStep)) {
             static::sendHandshake($connection);
         }
@@ -244,7 +246,7 @@ class Ws
                 if ($connection->onError) {
                     try {
                         ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package');
-                    } catch (\Throwable $e) {
+                    } catch (Throwable $e) {
                         Worker::stopAll(250, $e);
                     }
                 }
@@ -256,7 +258,7 @@ class Ws
                 if ($connection->onBufferFull) {
                     try {
                         ($connection->onBufferFull)($connection);
-                    } catch (\Throwable $e) {
+                    } catch (Throwable $e) {
                         Worker::stopAll(250, $e);
                     }
                 }
@@ -269,11 +271,11 @@ class Ws
     /**
      * Websocket decode.
      *
-     * @param string $buffer
-     * @param ConnectionInterface $connection
+     * @param string $bytes
+     * @param TcpConnection $connection
      * @return string
      */
-    public static function decode($bytes, ConnectionInterface $connection)
+    public static function decode(string $bytes, TcpConnection $connection): string
     {
         $dataLength = \ord($bytes[1]);
 
@@ -311,7 +313,7 @@ class Ws
      *
      * @param TcpConnection $connection
      */
-    public static function onClose($connection)
+    public static function onClose(TcpConnection $connection)
     {
         $connection->context->handshakeStep = null;
         $connection->context->websocketCurrentFrameLength = 0;
@@ -328,8 +330,9 @@ class Ws
      *
      * @param TcpConnection $connection
      * @return void
+     * @throws Throwable
      */
-    public static function sendHandshake(ConnectionInterface $connection)
+    public static function sendHandshake(TcpConnection $connection)
     {
         if (!empty($connection->context->handshakeStep)) {
             return;
@@ -372,8 +375,9 @@ class Ws
      * @param string $buffer
      * @param TcpConnection $connection
      * @return int
+     * @throws Throwable
      */
-    public static function dealHandshake($buffer, ConnectionInterface $connection)
+    public static function dealHandshake(string $buffer, TcpConnection $connection): bool|int
     {
         $pos = \strpos($buffer, "\r\n\r\n");
         if ($pos) {
@@ -403,7 +407,7 @@ class Ws
             if (isset($connection->onWebSocketConnect)) {
                 try {
                     ($connection->onWebSocketConnect)($connection, \substr($buffer, 0, $handshakeResponseLength));
-                } catch (\Throwable $e) {
+                } catch (Throwable $e) {
                     Worker::stopAll(250, $e);
                 }
             }

+ 19 - 19
src/Timer.php

@@ -36,24 +36,24 @@ class Timer
      *
      * @var array
      */
-    protected static $tasks = [];
+    protected static array $tasks = [];
 
     /**
-     * event
+     * Event
      *
-     * @var Select
+     * @var ?EventInterface
      */
-    protected static $event = null;
+    protected static ?EventInterface $event = null;
 
     /**
-     * timer id
+     * Timer id
      *
      * @var int
      */
-    protected static $timerId = 0;
+    protected static int $timerId = 0;
 
     /**
-     * timer status
+     * Timer status
      * [
      *   timer_id1 => bool,
      *   timer_id2 => bool,
@@ -62,15 +62,15 @@ class Timer
      *
      * @var array
      */
-    protected static $status = [];
+    protected static array $status = [];
 
     /**
      * Init.
      *
-     * @param EventInterface $event
+     * @param EventInterface|null $event
      * @return void
      */
-    public static function init($event = null)
+    public static function init(EventInterface $event = null)
     {
         if ($event) {
             self::$event = $event;
@@ -99,11 +99,11 @@ class Timer
      *
      * @param float    $timeInterval
      * @param callable $func
-     * @param mixed    $args
+     * @param mixed|array $args
      * @param bool $persistent
-     * @return int|bool
+     * @return int
      */
-    public static function add(float $timeInterval, callable $func, $args = [], bool $persistent = true)
+    public static function add(float $timeInterval, callable $func, null|array $args = [], bool $persistent = true): int
     {
         if ($timeInterval < 0) {
             throw new \RuntimeException('$timeInterval can not less than 0');
@@ -147,7 +147,7 @@ class Timer
      * Coroutine sleep.
      *
      * @param float $delay
-     * @return null
+     * @return void
      */
     public static function sleep(float $delay)
     {
@@ -159,15 +159,15 @@ class Timer
                     $suspension->resume();
                 }, null, false);
                 $suspension->suspend();
-                return null;
+                return;
             // Swoole
             case Swoole::class:
                 System::sleep($delay);
-                return null;
+                return;
             // Swow
             case Swow::class:
                 usleep($delay * 1000 * 1000);
-                return null;
+                return;
         }
         throw new \RuntimeException('Timer::sleep() require revolt/event-loop. Please run command "composer install revolt/event-loop" and restart workerman');
     }
@@ -210,10 +210,10 @@ class Timer
     /**
      * Remove a timer.
      *
-     * @param mixed $timerId
+     * @param int $timerId
      * @return bool
      */
-    public static function del($timerId)
+    public static function del(int $timerId): bool
     {
         if (self::$event) {
             return self::$event->offDelay($timerId);

+ 104 - 94
src/Worker.php

@@ -19,6 +19,7 @@ use Workerman\Connection\ConnectionInterface;
 use Workerman\Connection\TcpConnection;
 use Workerman\Connection\UdpConnection;
 use Workerman\Events\Event;
+use Workerman\Events\EventInterface;
 use Workerman\Events\Revolt;
 use Workerman\Events\Select;
 use Revolt\EventLoop;
@@ -91,68 +92,68 @@ class Worker
      *
      * @var int
      */
-    public $id = 0;
+    public int $id = 0;
 
     /**
      * Name of the worker processes.
      *
      * @var string
      */
-    public $name = 'none';
+    public string $name = 'none';
 
     /**
      * Number of worker processes.
      *
      * @var int
      */
-    public $count = 1;
+    public int $count = 1;
 
     /**
      * Unix user of processes, needs appropriate privileges (usually root).
      *
      * @var string
      */
-    public $user = '';
+    public string $user = '';
 
     /**
      * Unix group of processes, needs appropriate privileges (usually root).
      *
      * @var string
      */
-    public $group = '';
+    public string $group = '';
 
     /**
      * reloadable.
      *
      * @var bool
      */
-    public $reloadable = true;
+    public bool $reloadable = true;
 
     /**
      * reuse port.
      *
      * @var bool
      */
-    public $reusePort = false;
+    public bool $reusePort = false;
 
     /**
      * Emitted when worker processes start.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onWorkerStart = null;
 
     /**
      * Emitted when a socket connection is successfully established.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onConnect = null;
 
     /**
      * Emitted when websocket handshake completed (Only work when protocol is ws).
      *
-     * @var callable|null
+     * @var ?callable
      */
     public $onWebSocketConnect = null;
 
@@ -166,49 +167,49 @@ class Worker
     /**
      * Emitted when the other end of the socket sends a FIN packet.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onClose = null;
 
     /**
      * Emitted when an error occurs with connection.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onError = null;
 
     /**
      * Emitted when the send buffer becomes full.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onBufferFull = null;
 
     /**
      * Emitted when the send buffer becomes empty.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onBufferDrain = null;
 
     /**
      * Emitted when worker processes stopped.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onWorkerStop = null;
 
     /**
      * Emitted when worker processes get reload signal.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onWorkerReload = null;
 
     /**
      * Emitted when worker processes exited.
      *
-     * @var callable
+     * @var ?callable
      */
     public $onWorkerExit = null;
 
@@ -217,104 +218,104 @@ class Worker
      *
      * @var string
      */
-    public $transport = 'tcp';
+    public string $transport = 'tcp';
 
     /**
      * Store all connections of clients.
      *
      * @var array
      */
-    public $connections = [];
+    public array $connections = [];
 
     /**
      * Application layer protocol.
      *
-     * @var string
+     * @var ?string
      */
-    public $protocol = null;
+    public ?string $protocol = null;
 
     /**
      * Pause accept new connections or not.
      *
      * @var bool
      */
-    protected $pauseAccept = true;
+    protected bool $pauseAccept = true;
 
     /**
      * Is worker stopping ?
      * @var bool
      */
-    public $stopping = false;
+    public bool $stopping = false;
 
     /**
      * Daemonize.
      *
      * @var bool
      */
-    public static $daemonize = false;
+    public static bool $daemonize = false;
 
     /**
      * Stdout file.
      *
      * @var string
      */
-    public static $stdoutFile = '/dev/null';
+    public static string $stdoutFile = '/dev/null';
 
     /**
      * The file to store master process PID.
      *
      * @var string
      */
-    public static $pidFile = '';
+    public static string $pidFile = '';
 
     /**
      * The file used to store the master process status file.
      *
      * @var string
      */
-    public static $statusFile = '';
+    public static string $statusFile = '';
 
     /**
      * Log file.
      *
-     * @var string
+     * @var mixed
      */
-    public static $logFile = '';
+    public static mixed $logFile = '';
 
     /**
      * Global event loop.
      *
-     * @var Select
+     * @var ?EventInterface
      */
-    public static $globalEvent = null;
+    public static ?EventInterface $globalEvent = null;
 
     /**
      * Emitted when the master process get reload signal.
      *
-     * @var callable
+     * @var ?callable
      */
     public static $onMasterReload = null;
 
     /**
      * Emitted when the master process terminated.
      *
-     * @var callable
+     * @var ?callable
      */
     public static $onMasterStop = null;
 
     /**
      * EventLoopClass
      *
-     * @var string
+     * @var class-string
      */
-    public static $eventLoopClass = '';
+    public static string $eventLoopClass = '';
 
     /**
      * Process title
      *
      * @var string
      */
-    public static $processTitle = 'WorkerMan';
+    public static string $processTitle = 'WorkerMan';
 
     /**
      * After sending the stop command to the child process stopTimeout seconds,
@@ -322,20 +323,20 @@ class Worker
      *
      * @var int
      */
-    public static $stopTimeout = 2;
+    public static int $stopTimeout = 2;
 
     /**
      * Command
      * @var string
      */
-    public static $command = '';
+    public static string $command = '';
 
     /**
      * The PID of master process.
      *
      * @var int
      */
-    protected static $masterPid = 0;
+    protected static int $masterPid = 0;
 
     /**
      * Listening socket.
@@ -349,14 +350,14 @@ class Worker
      *
      * @var string
      */
-    protected $socketName = '';
+    protected string $socketName = '';
 
     /**
      * parse from socketName avoid parse again in master or worker
      * LocalSocket The format is like tcp://0.0.0.0:8080
-     * @var string
+     * @var ?string
      */
-    protected $localSocket = null;
+    protected ?string $localSocket = null;
 
     /**
      * Context of socket.
@@ -370,7 +371,7 @@ class Worker
      *
      * @var Worker[]
      */
-    protected static $workers = [];
+    protected static array $workers = [];
 
     /**
      * All worker processes pid.
@@ -378,7 +379,7 @@ class Worker
      *
      * @var array
      */
-    protected static $pidMap = [];
+    protected static array $pidMap = [];
 
     /**
      * All worker processes waiting for restart.
@@ -386,7 +387,7 @@ class Worker
      *
      * @var array
      */
-    protected static $pidsToRestart = [];
+    protected static array $pidsToRestart = [];
 
     /**
      * Mapping from PID to worker process ID.
@@ -394,84 +395,84 @@ class Worker
      *
      * @var array
      */
-    protected static $idMap = [];
+    protected static array $idMap = [];
 
     /**
      * Current status.
      *
      * @var int
      */
-    protected static $status = self::STATUS_STARTING;
+    protected static int $status = self::STATUS_STARTING;
 
     /**
      * Maximum length of the worker names.
      *
      * @var int
      */
-    protected static $maxWorkerNameLength = 12;
+    protected static int $maxWorkerNameLength = 12;
 
     /**
      * Maximum length of the socket names.
      *
      * @var int
      */
-    protected static $maxSocketNameLength = 12;
+    protected static int $maxSocketNameLength = 12;
 
     /**
      * Maximum length of the process user names.
      *
      * @var int
      */
-    protected static $maxUserNameLength = 12;
+    protected static int $maxUserNameLength = 12;
 
     /**
      * Maximum length of the Proto names.
      *
      * @var int
      */
-    protected static $maxProtoNameLength = 4;
+    protected static int $maxProtoNameLength = 4;
 
     /**
      * Maximum length of the Processes names.
      *
      * @var int
      */
-    protected static $maxProcessesNameLength = 9;
+    protected static int $maxProcessesNameLength = 9;
 
     /**
      * Maximum length of the state names.
      *
      * @var int
      */
-    protected static $maxStateNameLength = 1;
+    protected static int $maxStateNameLength = 1;
 
     /**
      * The file to store status info of current worker process.
      *
      * @var string
      */
-    protected static $statisticsFile = '';
+    protected static string $statisticsFile = '';
 
     /**
      * Start file.
      *
      * @var string
      */
-    protected static $startFile = '';
+    protected static string $startFile = '';
 
     /**
      * Processes for windows.
      *
      * @var array
      */
-    protected static $processForWindows = [];
+    protected static array $processForWindows = [];
 
     /**
      * Status info of current worker process.
      *
      * @var array
      */
-    protected static $globalStatistics = [
+    protected static array $globalStatistics = [
         'start_timestamp'  => 0,
         'worker_exit_info' => []
     ];
@@ -481,7 +482,7 @@ class Worker
      *
      * @var array<string, string>
      */
-    protected static $availableEventLoops = [
+    protected static array $availableEventLoops = [
         'event' => Event::class,
     ];
 
@@ -525,7 +526,7 @@ class Worker
      *
      * @var bool
      */
-    protected static $gracefulStop = false;
+    protected static bool $gracefulStop = false;
 
     /**
      * Standard output stream
@@ -537,14 +538,14 @@ class Worker
      * If $outputStream support decorated
      * @var bool
      */
-    protected static $outputDecorated = null;
+    protected static ?bool $outputDecorated = null;
 
     /**
      * Worker object's hash id(unique identifier).
      *
-     * @var string
+     * @var ?string
      */
-    protected $workerId = null;
+    protected ?string $workerId = null;
 
     /**
      * Run all worker instances.
@@ -664,6 +665,7 @@ class Worker
      * Init All worker instances.
      *
      * @return void
+     * @throws Exception
      */
     protected static function initWorkers()
     {
@@ -712,7 +714,7 @@ class Worker
      *
      * @return Worker[]
      */
-    public static function getAllWorkers()
+    public static function getAllWorkers(): array
     {
         return static::$workers;
     }
@@ -720,9 +722,9 @@ class Worker
     /**
      * Get global event-loop instance.
      *
-     * @return Select
+     * @return EventInterface
      */
-    public static function getEventLoop()
+    public static function getEventLoop(): EventInterface
     {
         return static::$globalEvent;
     }
@@ -757,7 +759,7 @@ class Worker
      *
      * @return string
      */
-    protected static function getCurrentUser()
+    protected static function getCurrentUser(): string
     {
         $userInfo = \posix_getpwuid(\posix_getuid());
         return $userInfo['name'];
@@ -833,7 +835,7 @@ class Worker
      *
      * @return array
      */
-    public static function getUiColumns()
+    public static function getUiColumns(): array
     {
         return [
             'proto'     => 'transport',
@@ -850,7 +852,7 @@ class Worker
      *
      * @return int
      */
-    public static function getSingleLineTotalLength()
+    public static function getSingleLineTotalLength(): int
     {
         $totalLength = 0;
 
@@ -1025,7 +1027,12 @@ class Worker
         }
     }
 
-    public static function getArgv()
+    /**
+     * Get argv.
+     *
+     * @return mixed
+     */
+    public static function getArgv(): mixed
     {
         global $argv;
         return isset($argv[1]) ? $argv : (static::$command ? \explode(' ', static::$command) : $argv);
@@ -1037,7 +1044,7 @@ class Worker
      * @param $statisticsFile
      * @return string
      */
-    protected static function formatStatusData($statisticsFile)
+    protected static function formatStatusData($statisticsFile): string
     {
         static $totalRequestCache = [];
         if (!\is_readable($statisticsFile)) {
@@ -1154,8 +1161,9 @@ class Worker
      * Signal handler.
      *
      * @param int $signal
+     * @throws Exception
      */
-    public static function signalHandler($signal)
+    public static function signalHandler(int $signal)
     {
         switch ($signal) {
             // Stop.
@@ -1320,7 +1328,7 @@ class Worker
      *
      * @return array
      */
-    protected static function getAllWorkerPids()
+    protected static function getAllWorkerPids(): array
     {
         $pidArray = [];
         foreach (static::$pidMap as $workerPidArray) {
@@ -1349,6 +1357,7 @@ class Worker
      * Fork some worker processes.
      *
      * @return void
+     * @throws Exception
      */
     protected static function forkWorkersForLinux()
     {
@@ -1374,6 +1383,7 @@ class Worker
      * Fork some worker processes.
      *
      * @return void
+     * @throws Exception
      */
     protected static function forkWorkersForWindows()
     {
@@ -1419,7 +1429,8 @@ class Worker
      *
      * @return array
      */
-    public static function getStartFilesForWindows() {
+    public static function getStartFilesForWindows(): array
+    {
         $files = [];
         foreach(static::getArgv() as $file)
         {
@@ -1436,7 +1447,7 @@ class Worker
      *
      * @param string $startFile
      */
-    public static function forkOneWorkerForWindows($startFile)
+    public static function forkOneWorkerForWindows(string $startFile)
     {
         $startFile = \realpath($startFile);
 
@@ -1486,7 +1497,6 @@ class Worker
         }
     }
 
-
     /**
      * Fork one worker process.
      *
@@ -1543,9 +1553,9 @@ class Worker
      * @param string $workerId
      * @param int $pid
      *
-     * @return integer
+     * @return false|int|string
      */
-    protected static function getId($workerId, $pid)
+    protected static function getId(string $workerId, int $pid): bool|int|string
     {
         return \array_search($pid, static::$idMap[$workerId]);
     }
@@ -1615,6 +1625,7 @@ class Worker
      * Monitor all child processes.
      *
      * @return void
+     * @throws Exception
      */
     protected static function monitorWorkersForLinux()
     {
@@ -1699,8 +1710,6 @@ class Worker
 
     /**
      * Exit current process.
-     *
-     * @return void
      */
     protected static function exitAndClearAll()
     {
@@ -1808,9 +1817,9 @@ class Worker
      * Stop all.
      *
      * @param int $code
-     * @param string $log
+     * @param mixed $log
      */
-    public static function stopAll($code = 0, $log = '')
+    public static function stopAll(int $code = 0, mixed $log = '')
     {
         if ($log) {
             static::log($log);
@@ -1880,9 +1889,9 @@ class Worker
     /**
      * Get process status.
      *
-     * @return number
+     * @return int
      */
-    public static function getStatus()
+    public static function getStatus(): int
     {
         return static::$status;
     }
@@ -1892,7 +1901,7 @@ class Worker
      *
      * @return bool
      */
-    public static function getGracefulStop()
+    public static function getGracefulStop(): bool
     {
         return static::$gracefulStop;
     }
@@ -2084,10 +2093,10 @@ class Worker
     /**
      * Get error message by error code.
      *
-     * @param integer $type
+     * @param int $type
      * @return string
      */
-    protected static function getErrorType($type)
+    protected static function getErrorType(int $type): string
     {
         return self::ERROR_TYPE[$type] ?? '';
     }
@@ -2095,10 +2104,10 @@ class Worker
     /**
      * Log.
      *
-     * @param string $msg
+     * @param mixed $msg
      * @return void
      */
-    public static function log($msg)
+    public static function log(mixed $msg)
     {
         $msg = $msg . "\n";
         if (!static::$daemonize) {
@@ -2171,7 +2180,7 @@ class Worker
     /**
      * Constructor.
      *
-     * @param string $socketName
+     * @param string|null $socketName
      * @param array $contextOption
      */
     public function __construct(string $socketName = null, array $contextOption = [])
@@ -2293,7 +2302,8 @@ class Worker
      *
      * @throws Exception
      */
-    protected function parseSocketAddress() {
+    protected function parseSocketAddress(): ?string
+    {
         if (!$this->socketName) {
             return null;
         }
@@ -2358,7 +2368,7 @@ class Worker
      *
      * @return string
      */
-    public function getSocketName()
+    public function getSocketName(): string
     {
         return $this->socketName ? \lcfirst($this->socketName) : 'none';
     }
@@ -2487,7 +2497,7 @@ class Worker
      * @param resource $socket
      * @return bool
      */
-    public function acceptUdpConnection($socket)
+    public function acceptUdpConnection($socket): bool
     {
         \set_error_handler(function(){});
         $recvBuffer = \stream_socket_recvfrom($socket, static::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress);
@@ -2542,13 +2552,13 @@ class Worker
      * @param int $masterPid
      * @return bool
      */
-    protected static function checkMasterIsAlive($masterPid)
+    protected static function checkMasterIsAlive(int $masterPid): bool
     {
         if (empty($masterPid)) {
             return false;
         }
 
-        $masterIsAlive = $masterPid && \posix_kill((int) $masterPid, 0) && \posix_getpid() !== $masterPid;
+        $masterIsAlive = $masterPid && \posix_kill($masterPid, 0) && \posix_getpid() !== $masterPid;
         if (!$masterIsAlive) {
             return false;
         }