Forráskód Böngészése

Added missing types and corrected grammar errors.

Ako Tulu 2 éve
szülő
commit
0ebb749660

+ 1 - 1
src/Protocols/Http.php

@@ -135,7 +135,7 @@ class Http
             $length = $length + (int)substr($header, $pos + 18, 10);
             $hasContentLength = true;
         } else if (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) {
-            $length = $length + $match[1];
+            $length = $length + (int)$match[1];
             $hasContentLength = true;
         } else {
             $hasContentLength = false;

+ 9 - 9
src/Protocols/Http/Request.php

@@ -188,7 +188,7 @@ class Request
      * @param string|null $name
      * @return array|null
      */
-    public function file(string $name = null)
+    public function file(string $name = null): ?array
     {
         if (!isset($this->data['files'])) {
             $this->parsePost();
@@ -382,7 +382,7 @@ class Request
      *
      * @param bool $value
      */
-    public static function enableCache(bool $value)
+    public static function enableCache(bool $value): void
     {
         static::$enableCache = $value;
     }
@@ -392,7 +392,7 @@ class Request
      *
      * @return void
      */
-    protected function parseHeadFirstLine()
+    protected function parseHeadFirstLine(): void
     {
         $firstLine = strstr($this->buffer, "\r\n", true);
         $tmp = explode(' ', $firstLine, 3);
@@ -405,7 +405,7 @@ class Request
      *
      * @return void
      */
-    protected function parseProtocolVersion()
+    protected function parseProtocolVersion(): void
     {
         $firstLine = strstr($this->buffer, "\r\n", true);
         $protocolVersion = substr(strstr($firstLine, 'HTTP/'), 5);
@@ -417,7 +417,7 @@ class Request
      *
      * @return void
      */
-    protected function parseHeaders()
+    protected function parseHeaders(): void
     {
         static $cache = [];
         $this->data['headers'] = [];
@@ -461,7 +461,7 @@ class Request
      *
      * @return void
      */
-    protected function parseGet()
+    protected function parseGet(): void
     {
         static $cache = [];
         $queryString = $this->queryString();
@@ -488,7 +488,7 @@ class Request
      *
      * @return void
      */
-    protected function parsePost()
+    protected function parsePost(): void
     {
         static $cache = [];
         $this->data['post'] = $this->data['files'] = [];
@@ -526,7 +526,7 @@ class Request
      * @param string $httpPostBoundary
      * @return void
      */
-    protected function parseUploadFiles(string $httpPostBoundary)
+    protected function parseUploadFiles(string $httpPostBoundary): void
     {
         $httpPostBoundary = trim($httpPostBoundary, '"');
         $buffer = $this->buffer;
@@ -654,7 +654,7 @@ class Request
      * @param array $cookieParams
      * @return void
      */
-    protected function setSidCookie(string $sessionName, string $sid, array $cookieParams)
+    protected function setSidCookie(string $sessionName, string $sid, array $cookieParams): void
     {
         if (!$this->connection) {
             throw new RuntimeException('Request->setSidCookie() fail, header already send');

+ 7 - 7
src/Protocols/Http/Response.php

@@ -167,7 +167,7 @@ class Response
      *
      * @return void
      */
-    public static function init()
+    public static function init(): void
     {
         static::initMimeTypeMap();
     }
@@ -176,13 +176,13 @@ class Response
      * Response constructor.
      *
      * @param int $status
-     * @param array $headers
+     * @param array|null $headers
      * @param string $body
      */
     public function __construct(
-        int    $status = 200,
-        array  $headers = [],
-        string $body = ''
+        int     $status = 200,
+        ?array  $headers = [],
+        string  $body = ''
     )
     {
         $this->status = $status;
@@ -208,7 +208,7 @@ class Response
      *
      * @param string $name
      * @param string $value
-     * @return Response
+     * @return $this
      */
     public function withHeader(string $name, string $value): static
     {
@@ -480,7 +480,7 @@ class Response
      *
      * @return void
      */
-    public static function initMimeTypeMap()
+    public static function initMimeTypeMap(): void
     {
         $mimeFile = __DIR__ . '/mime.types';
         $items = file($mimeFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

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

@@ -16,6 +16,7 @@ declare(strict_types=1);
 
 namespace Workerman\Protocols\Http\Session;
 
+use Exception;
 use Workerman\Protocols\Http\Session;
 use function clearstatcache;
 use function file_get_contents;
@@ -104,6 +105,7 @@ class FileSessionHandler implements SessionHandlerInterface
 
     /**
      * {@inheritdoc}
+     * @throws Exception
      */
     public function write(string $sessionId, string $sessionData): bool
     {
@@ -115,7 +117,7 @@ class FileSessionHandler implements SessionHandlerInterface
     }
 
     /**
-     * Update sesstion modify time.
+     * Update session modify time.
      *
      * @see https://www.php.net/manual/en/class.sessionupdatetimestamphandlerinterface.php
      * @see https://www.php.net/manual/zh/function.touch.php

+ 2 - 0
src/Protocols/Http/Session/RedisClusterSessionHandler.php

@@ -19,12 +19,14 @@ namespace Workerman\Protocols\Http\Session;
 use Redis;
 use RedisCluster;
 use RedisClusterException;
+use RedisException;
 
 class RedisClusterSessionHandler extends RedisSessionHandler
 {
     /**
      * @param $config
      * @throws RedisClusterException
+     * @throws RedisException
      */
     public function __construct($config)
     {

+ 13 - 3
src/Protocols/Http/Session/RedisSessionHandler.php

@@ -17,6 +17,7 @@ declare(strict_types=1);
 namespace Workerman\Protocols\Http\Session;
 
 use Redis;
+use RedisCluster;
 use RedisException;
 use RuntimeException;
 use Throwable;
@@ -29,11 +30,10 @@ use Workerman\Timer;
  */
 class RedisSessionHandler implements SessionHandlerInterface
 {
-
     /**
-     * @var Redis
+     * @var Redis|RedisCluster
      */
-    protected Redis $redis;
+    protected Redis|RedisCluster $redis;
 
     /**
      * @var array
@@ -51,6 +51,7 @@ class RedisSessionHandler implements SessionHandlerInterface
      *  'prefix'   => 'redis_session_',
      *  'ping'     => 55,
      * ]
+     * @throws RedisException
      */
     public function __construct(array $config)
     {
@@ -71,6 +72,9 @@ class RedisSessionHandler implements SessionHandlerInterface
         });
     }
 
+    /**
+     * @throws RedisException
+     */
     public function connect()
     {
         $config = $this->config;
@@ -101,7 +105,10 @@ class RedisSessionHandler implements SessionHandlerInterface
 
     /**
      * {@inheritdoc}
+     * @param string $sessionId
+     * @return string
      * @throws RedisException
+     * @throws Throwable
      */
     public function read(string $sessionId): string
     {
@@ -119,6 +126,7 @@ class RedisSessionHandler implements SessionHandlerInterface
 
     /**
      * {@inheritdoc}
+     * @throws RedisException
      */
     public function write(string $sessionId, string $sessionData): bool
     {
@@ -127,6 +135,7 @@ class RedisSessionHandler implements SessionHandlerInterface
 
     /**
      * {@inheritdoc}
+     * @throws RedisException
      */
     public function updateTimestamp(string $sessionId, string $data = ""): bool
     {
@@ -135,6 +144,7 @@ class RedisSessionHandler implements SessionHandlerInterface
 
     /**
      * {@inheritdoc}
+     * @throws RedisException
      */
     public function destroy(string $sessionId): bool
     {

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

@@ -103,7 +103,7 @@ interface SessionHandlerInterface
     public function write(string $sessionId, string $sessionData): bool;
 
     /**
-     * Update sesstion modify time.
+     * Update session modify time.
      *
      * @see https://www.php.net/manual/en/class.sessionupdatetimestamphandlerinterface.php
      *

+ 4 - 4
src/Protocols/Ws.php

@@ -324,11 +324,11 @@ class Ws
     /**
      * Send websocket handshake data.
      *
-     * @param $connection
+     * @param AsyncTcpConnection $connection
      * @return void
      * @throws Throwable
      */
-    public static function onConnect($connection)
+    public static function onConnect(AsyncTcpConnection $connection): void
     {
         static::sendHandshake($connection);
     }
@@ -338,7 +338,7 @@ class Ws
      *
      * @param AsyncTcpConnection $connection
      */
-    public static function onClose(AsyncTcpConnection $connection)
+    public static function onClose(AsyncTcpConnection $connection): void
     {
         $connection->context->handshakeStep = null;
         $connection->context->websocketCurrentFrameLength = 0;
@@ -357,7 +357,7 @@ class Ws
      * @return void
      * @throws Throwable
      */
-    public static function sendHandshake(AsyncTcpConnection $connection)
+    public static function sendHandshake(AsyncTcpConnection $connection): void
     {
         if (!empty($connection->context->handshakeStep)) {
             return;

+ 6 - 8
src/Timer.php

@@ -82,7 +82,7 @@ class Timer
      * @param EventInterface|null $event
      * @return void
      */
-    public static function init(EventInterface $event = null)
+    public static function init(EventInterface $event = null): void
     {
         if ($event) {
             self::$event = $event;
@@ -98,7 +98,7 @@ class Timer
      *
      * @return void
      */
-    public static function signalHandle()
+    public static function signalHandle(): void
     {
         if (!self::$event) {
             pcntl_alarm(1);
@@ -156,7 +156,7 @@ class Timer
      * @param float $delay
      * @return void
      */
-    public static function sleep(float $delay)
+    public static function sleep(float $delay): void
     {
         switch (Worker::$eventLoopClass) {
             // Fiber
@@ -184,7 +184,7 @@ class Timer
      *
      * @return void
      */
-    public static function tick()
+    public static function tick(): void
     {
         if (empty(self::$tasks)) {
             pcntl_alarm(0);
@@ -241,14 +241,12 @@ class Timer
      *
      * @return void
      */
-    public static function delAll()
+    public static function delAll(): void
     {
         self::$tasks = self::$status = [];
         if (function_exists('pcntl_alarm')) {
             pcntl_alarm(0);
         }
-        if (self::$event) {
-            self::$event->deleteAllTimer();
-        }
+        self::$event?->deleteAllTimer();
     }
 }

+ 28 - 28
src/Worker.php

@@ -422,7 +422,7 @@ class Worker
     protected static int $maxSocketNameLength = 12;
 
     /**
-     * Maximum length of the process user names.
+     * Maximum length of the process usernames.
      *
      * @var int
      */
@@ -554,7 +554,7 @@ class Worker
      * Run all worker instances.
      *
      * @return void
-     * @throws Exception
+     * @throws Throwable
      */
     public static function runAll(): void
     {
@@ -644,7 +644,7 @@ class Worker
      * @param int $flag
      * @return void
      */
-    protected static function lock($flag = \LOCK_EX): void
+    protected static function lock(int $flag = \LOCK_EX): void
     {
         static $fd;
         if (\DIRECTORY_SEPARATOR !== '/') {
@@ -803,7 +803,7 @@ class Worker
             $key = 'max' . \ucfirst(\strtolower($columnName)) . 'NameLength';
             //just keep compatible with listen name
             $columnName === 'socket' && $columnName = 'listen';
-            $title .= "<w>{$columnName}</w>" . \str_pad('', static::$$key + static::UI_SAFE_LENGTH - \strlen($columnName));
+            $title .= "<w>$columnName</w>" . \str_pad('', static::$$key + static::UI_SAFE_LENGTH - \strlen($columnName));
         }
         $title && static::safeEcho($title . \PHP_EOL);
 
@@ -813,7 +813,7 @@ class Worker
             foreach (static::getUiColumns() as $columnName => $prop) {
                 $propValue = (string)($worker->$prop ?? $worker->context->$prop);
                 $key = 'max' . \ucfirst(\strtolower($columnName)) . 'NameLength';
-                \preg_match_all("/(<n>|<\/n>|<w>|<\/w>|<g>|<\/g>)/is", $propValue, $matches);
+                \preg_match_all("/(<n>|<\/n>|<w>|<\/w>|<g>|<\/g>)/i", $propValue, $matches);
                 $placeHolderLength = !empty($matches) ? \strlen(\implode('', $matches[0])) : 0;
                 $content .= \str_pad($propValue, static::$$key + static::UI_SAFE_LENGTH + $placeHolderLength);
             }
@@ -1037,9 +1037,9 @@ class Worker
     /**
      * Get argv.
      *
-     * @return mixed
+     * @return array
      */
-    public static function getArgv(): mixed
+    public static function getArgv(): array
     {
         global $argv;
         return isset($argv[1]) ? $argv : (static::$command ? \explode(' ', static::$command) : $argv);
@@ -1151,6 +1151,7 @@ class Worker
      * Reinstall signal handler.
      *
      * @return void
+     * @throws Throwable
      */
     protected static function reinstallSignal(): void
     {
@@ -1161,7 +1162,7 @@ class Worker
         foreach ($signals as $signal) {
             \pcntl_signal($signal, \SIG_IGN, false);
             static::$globalEvent->onSignal($signal, [static::class, 'signalHandler']);
-        };
+        }
     }
 
     /**
@@ -1354,7 +1355,7 @@ class Worker
      * Fork some worker processes.
      *
      * @return void
-     * @throws Exception
+     * @throws Throwable
      */
     protected static function forkWorkers(): void
     {
@@ -1369,7 +1370,7 @@ class Worker
      * Fork some worker processes.
      *
      * @return void
-     * @throws Exception
+     * @throws Throwable
      */
     protected static function forkWorkersForLinux(): void
     {
@@ -1395,7 +1396,7 @@ class Worker
      * Fork some worker processes.
      *
      * @return void
-     * @throws Exception
+     * @throws Throwable
      */
     protected static function forkWorkersForWindows(): void
     {
@@ -1485,12 +1486,12 @@ class Worker
     {
         $startFile = \realpath($startFile);
 
-        $descriptorspec = array(
+        $descriptor_spec = array(
             STDIN, STDOUT, STDOUT
         );
 
         $pipes = array();
-        $process = \proc_open('"' . PHP_BINARY . '" '  . " \"$startFile\" -q", $descriptorspec, $pipes, null, null, ['bypass_shell' => true]);
+        $process = \proc_open('"' . PHP_BINARY . '" '  . " \"$startFile\" -q", $descriptor_spec, $pipes, null, null, ['bypass_shell' => true]);
 
         if (empty(static::$globalEvent)) {
             static::$globalEvent = new Select();
@@ -1622,7 +1623,7 @@ class Worker
         // Get uid.
         $userInfo = \posix_getpwnam($this->user);
         if (!$userInfo) {
-            static::log("Warning: User {$this->user} not exists");
+            static::log("Warning: User $this->user not exists");
             return;
         }
         $uid = $userInfo['uid'];
@@ -1630,7 +1631,7 @@ class Worker
         if ($this->group) {
             $groupInfo = \posix_getgrnam($this->group);
             if (!$groupInfo) {
-                static::log("Warning: Group {$this->group} not exists");
+                static::log("Warning: Group $this->group not exists");
                 return;
             }
             $gid = $groupInfo['gid'];
@@ -1664,7 +1665,7 @@ class Worker
      * Monitor all child processes.
      *
      * @return void
-     * @throws Exception
+     * @throws Throwable
      */
     protected static function monitorWorkers(): void
     {
@@ -1679,7 +1680,7 @@ class Worker
      * Monitor all child processes.
      *
      * @return void
-     * @throws Exception
+     * @throws Throwable
      */
     protected static function monitorWorkersForLinux(): void
     {
@@ -1704,7 +1705,7 @@ class Worker
                         }
                         // Exit status.
                         if ($status !== 0) {
-                            static::log("worker[{$worker->name}:$pid] exit with status $status");
+                            static::log("worker[$worker->name:$pid] exit with status $status");
                         }
 
                         // onWorkerExit
@@ -1712,7 +1713,7 @@ class Worker
                             try {
                                 (static::$onWorkerExit)($worker, $status, $pid);
                             } catch (Throwable $exception) {
-                                static::log("worker[{$worker->name}] onWorkerExit $exception");
+                                static::log("worker[$worker->name] onWorkerExit $exception");
                             }
                         }
 
@@ -1754,6 +1755,7 @@ class Worker
      * Monitor all child processes.
      *
      * @return void
+     * @throws Throwable
      */
     protected static function monitorWorkersForWindows(): void
     {
@@ -1765,7 +1767,7 @@ class Worker
     /**
      * Exit current process.
      */
-    protected static function exitAndClearAll()
+    protected static function exitAndClearAll(): void
     {
         foreach (static::$workers as $worker) {
             $socketName = $worker->getSocketName();
@@ -1912,9 +1914,7 @@ class Worker
             }
             if (!static::$gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
                 static::$workers = [];
-                if (static::$globalEvent) {
-                    static::$globalEvent->stop();
-                }
+                static::$globalEvent?->stop();
 
                 try {
                     exit($code);
@@ -2032,7 +2032,7 @@ class Worker
         \reset(static::$workers);
         /** @var static $worker */
         $worker = current(static::$workers);
-        $workerStatusStr = \posix_getpid() . "\t" . \str_pad((string)round(memory_get_usage() / (1024 * 1024), 2) . "M", 7)
+        $workerStatusStr = \posix_getpid() . "\t" . \str_pad(round(memory_get_usage() / (1024 * 1024), 2) . "M", 7)
             . " " . \str_pad($worker->getSocketName(), static::$maxSocketNameLength) . " "
             . \str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$maxWorkerNameLength)
             . " ";
@@ -2086,7 +2086,7 @@ class Worker
 
         /** @var static $worker */
         foreach (TcpConnection::$connections as $connection) {
-            /** @var \Workerman\Connection\TcpConnection $connection */
+            /** @var TcpConnection $connection */
             $transport = $connection->transport;
             $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
             $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
@@ -2098,7 +2098,7 @@ class Worker
             $bytesRead = $bytesFormat($connection->bytesRead);
             $bytesWritten = $bytesFormat($connection->bytesWritten);
             $id = $connection->id;
-            $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
+            $protocol = $connection->protocol ?: $connection->transport;
             $pos = \strrpos($protocol, '\\');
             if ($pos) {
                 $protocol = \substr($protocol, $pos + 1);
@@ -2591,12 +2591,12 @@ class Worker
             return false;
         }
 
-        $masterIsAlive = $masterPid && \posix_kill($masterPid, 0) && \posix_getpid() !== $masterPid;
+        $masterIsAlive = \posix_kill($masterPid, 0) && \posix_getpid() !== $masterPid;
         if (!$masterIsAlive) {
             return false;
         }
 
-        $cmdline = "/proc/{$masterPid}/cmdline";
+        $cmdline = "/proc/$masterPid/cmdline";
         if (!is_readable($cmdline) || empty(static::$processTitle)) {
             return true;
         }