walkor пре 2 година
родитељ
комит
c229f936dc

+ 23 - 23
src/Connection/AsyncTcpConnection.php

@@ -120,39 +120,39 @@ class AsyncTcpConnection extends TcpConnection
     /**
      * Construct.
      *
-     * @param string $remote_address
-     * @param array $context_option
+     * @param string $remoteAddress
+     * @param array $contextOption
      * @throws Exception
      */
-    public function __construct($remote_address, array $context_option = [])
+    public function __construct($remoteAddress, array $contextOption = [])
     {
-        $address_info = \parse_url($remote_address);
-        if (!$address_info) {
-            list($scheme, $this->remoteAddress) = \explode(':', $remote_address, 2);
+        $addressInfo = \parse_url($remoteAddress);
+        if (!$addressInfo) {
+            list($scheme, $this->remoteAddress) = \explode(':', $remoteAddress, 2);
             if ('unix' === strtolower($scheme)) {
-                $this->remoteAddress = substr($remote_address, strpos($remote_address, '/') + 2);
+                $this->remoteAddress = substr($remoteAddress, strpos($remoteAddress, '/') + 2);
             }
             if (!$this->remoteAddress) {
                 Worker::safeEcho(new \Exception('bad remote_address'));
             }
         } else {
-            if (!isset($address_info['port'])) {
-                $address_info['port'] = 0;
+            if (!isset($addressInfo['port'])) {
+                $addressInfo['port'] = 0;
             }
-            if (!isset($address_info['path'])) {
-                $address_info['path'] = '/';
+            if (!isset($addressInfo['path'])) {
+                $addressInfo['path'] = '/';
             }
-            if (!isset($address_info['query'])) {
-                $address_info['query'] = '';
+            if (!isset($addressInfo['query'])) {
+                $addressInfo['query'] = '';
             } else {
-                $address_info['query'] = '?' . $address_info['query'];
+                $addressInfo['query'] = '?' . $addressInfo['query'];
             }
-            $this->remoteHost = $address_info['host'];
-            $this->remotePort = $address_info['port'];
-            $this->remoteURI = "{$address_info['path']}{$address_info['query']}";
-            $scheme = $address_info['scheme'] ?? 'tcp';
+            $this->remoteHost = $addressInfo['host'];
+            $this->remotePort = $addressInfo['port'];
+            $this->remoteURI = "{$addressInfo['path']}{$addressInfo['query']}";
+            $scheme = $addressInfo['scheme'] ?? 'tcp';
             $this->remoteAddress = 'unix' === strtolower($scheme)
-                ? substr($remote_address, strpos($remote_address, '/') + 2)
+                ? substr($remoteAddress, strpos($remoteAddress, '/') + 2)
                 : $this->remoteHost . ':' . $this->remotePort;
         }
 
@@ -178,7 +178,7 @@ class AsyncTcpConnection extends TcpConnection
         ++self::$statistics['connection_count'];
         $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
         $this->maxPackageSize = self::$defaultMaxPackageSize;
-        $this->contextOption = $context_option;
+        $this->contextOption = $contextOption;
         static::$connections[$this->realId] = $this;
     }
 
@@ -348,9 +348,9 @@ class AsyncTcpConnection extends TcpConnection
             }
             // Try to open keepalive for tcp and disable Nagle algorithm.
             if (\function_exists('socket_import_stream') && $this->transport === 'tcp') {
-                $raw_socket = \socket_import_stream($this->socket);
-                \socket_set_option($raw_socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
-                \socket_set_option($raw_socket, \SOL_TCP, \TCP_NODELAY, 1);
+                $rawSocket = \socket_import_stream($this->socket);
+                \socket_set_option($rawSocket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
+                \socket_set_option($rawSocket, \SOL_TCP, \TCP_NODELAY, 1);
             }
             // SSL handshake.
             if ($this->transport === 'ssl') {

+ 13 - 13
src/Connection/AsyncUdpConnection.php

@@ -54,13 +54,13 @@ class AsyncUdpConnection extends UdpConnection
     /**
      * Construct.
      *
-     * @param string $remote_address
+     * @param string $remoteAddress
      * @throws Exception
      */
-    public function __construct($remote_address, $context_option = null)
+    public function __construct($remoteAddress, $contextOption = null)
     {
         // Get the application layer communication protocol and listening address.
-        list($scheme, $address) = \explode(':', $remote_address, 2);
+        list($scheme, $address) = \explode(':', $remoteAddress, 2);
         // Check application layer protocol class.
         if ($scheme !== 'udp') {
             $scheme = \ucfirst($scheme);
@@ -74,7 +74,7 @@ class AsyncUdpConnection extends UdpConnection
         }
 
         $this->remoteAddress = \substr($address, 2);
-        $this->contextOption = $context_option;
+        $this->contextOption = $contextOption;
     }
 
     /**
@@ -85,18 +85,18 @@ class AsyncUdpConnection extends UdpConnection
      */
     public function baseRead($socket)
     {
-        $recv_buffer = \stream_socket_recvfrom($socket, Worker::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
-        if (false === $recv_buffer || empty($remote_address)) {
+        $recvBuffer = \stream_socket_recvfrom($socket, Worker::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress);
+        if (false === $recvBuffer || empty($remoteAddress)) {
             return false;
         }
 
         if ($this->onMessage) {
             if ($this->protocol) {
-                $recv_buffer = $this->protocol::decode($recv_buffer, $this);
+                $recvBuffer = $this->protocol::decode($recvBuffer, $this);
             }
             ++ConnectionInterface::$statistics['total_request'];
             try {
-                ($this->onMessage)($this, $recv_buffer);
+                ($this->onMessage)($this, $recvBuffer);
             } catch (\Throwable $e) {
                 Worker::stopAll(250, $e);
             }
@@ -107,23 +107,23 @@ class AsyncUdpConnection extends UdpConnection
     /**
      * Sends data on the connection.
      *
-     * @param string $send_buffer
+     * @param string $sendBuffer
      * @param bool $raw
      * @return void|boolean
      */
-    public function send($send_buffer, $raw = false)
+    public function send($sendBuffer, $raw = false)
     {
         if (false === $raw && $this->protocol) {
             $parser = $this->protocol;
-            $send_buffer = $parser::encode($send_buffer, $this);
-            if ($send_buffer === '') {
+            $sendBuffer = $parser::encode($sendBuffer, $this);
+            if ($sendBuffer === '') {
                 return;
             }
         }
         if ($this->connected === false) {
             $this->connect();
         }
-        return \strlen($send_buffer) === \stream_socket_sendto($this->socket, $send_buffer, 0);
+        return \strlen($sendBuffer) === \stream_socket_sendto($this->socket, $sendBuffer, 0);
     }
 
 

+ 2 - 2
src/Connection/ConnectionInterface.php

@@ -77,10 +77,10 @@ abstract class ConnectionInterface
     /**
      * Sends data on the connection.
      *
-     * @param mixed $send_buffer
+     * @param mixed $sendBuffer
      * @return void|boolean
      */
-    abstract public function send($send_buffer);
+    abstract public function send($sendBuffer);
 
     /**
      * Get remote IP.

+ 26 - 26
src/Connection/TcpConnection.php

@@ -280,9 +280,9 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * Construct.
      *
      * @param resource $socket
-     * @param string $remote_address
+     * @param string $remoteAddress
      */
-    public function __construct($socket, $remote_address = '')
+    public function __construct($socket, $remoteAddress = '')
     {
         ++self::$statistics['connection_count'];
         $this->id = $this->realId = self::$idRecorder++;
@@ -298,7 +298,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         Worker::$globalEvent->onReadable($this->socket, [$this, 'baseRead']);
         $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
         $this->maxPackageSize = self::$defaultMaxPackageSize;
-        $this->remoteAddress = $remote_address;
+        $this->remoteAddress = $remoteAddress;
         static::$connections[$this->id] = $this;
         $this->context = new \stdClass;
     }
@@ -306,13 +306,13 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Get status.
      *
-     * @param bool $raw_output
+     * @param bool $rawOutput
      *
      * @return int|string
      */
-    public function getStatus($raw_output = true)
+    public function getStatus($rawOutput = true)
     {
-        if ($raw_output) {
+        if ($rawOutput) {
             return $this->status;
         }
         return self::$statusToString[$this->status];
@@ -321,20 +321,20 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
     /**
      * Sends data on the connection.
      *
-     * @param mixed $send_buffer
+     * @param mixed $sendBuffer
      * @param bool $raw
      * @return bool|null
      */
-    public function send($send_buffer, $raw = false)
+    public function send($sendBuffer, $raw = false)
     {
         if ($this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) {
             return false;
         }
 
-        // Try to call protocol::encode($send_buffer) before sending.
+        // Try to call protocol::encode($sendBuffer) before sending.
         if (false === $raw && $this->protocol !== null) {
-            $send_buffer = $this->protocol::encode($send_buffer, $this);
-            if ($send_buffer === '') {
+            $sendBuffer = $this->protocol::encode($sendBuffer, $this);
+            if ($sendBuffer === '') {
                 return;
             }
         }
@@ -346,7 +346,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                 ++self::$statistics['send_fail'];
                 return false;
             }
-            $this->sendBuffer .= $send_buffer;
+            $this->sendBuffer .= $sendBuffer;
             $this->checkBufferWillFull();
             return;
         }
@@ -355,24 +355,24 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
         if ($this->sendBuffer === '') {
             if ($this->transport === 'ssl') {
                 Worker::$globalEvent->onWritable($this->socket, [$this, 'baseWrite']);
-                $this->sendBuffer = $send_buffer;
+                $this->sendBuffer = $sendBuffer;
                 $this->checkBufferWillFull();
                 return;
             }
             $len = 0;
             try {
-                $len = @\fwrite($this->socket, $send_buffer);
+                $len = @\fwrite($this->socket, $sendBuffer);
             } catch (\Throwable $e) {
                 Worker::log($e);
             }
             // send successful.
-            if ($len === \strlen($send_buffer)) {
+            if ($len === \strlen($sendBuffer)) {
                 $this->bytesWritten += $len;
                 return true;
             }
             // Send only part of the data.
             if ($len > 0) {
-                $this->sendBuffer = \substr($send_buffer, $len);
+                $this->sendBuffer = \substr($sendBuffer, $len);
                 $this->bytesWritten += $len;
             } else {
                 // Connection closed?
@@ -388,7 +388,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                     $this->destroy();
                     return false;
                 }
-                $this->sendBuffer = $send_buffer;
+                $this->sendBuffer = $sendBuffer;
             }
             Worker::$globalEvent->onWritable($this->socket, [$this, 'baseWrite']);
             // Check if the send buffer will be full.
@@ -401,7 +401,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
             return false;
         }
 
-        $this->sendBuffer .= $send_buffer;
+        $this->sendBuffer .= $sendBuffer;
         // Check if the send buffer is full.
         $this->checkBufferWillFull();
     }
@@ -562,10 +562,10 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
      * Base read handler.
      *
      * @param resource $socket
-     * @param bool $check_eof
+     * @param bool $checkEof
      * @return void
      */
-    public function baseRead($socket, $check_eof = true)
+    public function baseRead($socket, $checkEof = true)
     {
         static $requests = [];
         // SSL handshake.
@@ -588,7 +588,7 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
 
         // Check connection closed.
         if ($buffer === '' || $buffer === false) {
-            if ($check_eof && (\feof($socket) || !\is_resource($socket) || $buffer === false)) {
+            if ($checkEof && (\feof($socket) || !\is_resource($socket) || $buffer === false)) {
                 $this->destroy();
                 return;
             }
@@ -653,11 +653,11 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                 ++self::$statistics['total_request'];
                 // The current packet length is equal to the length of the buffer.
                 if ($one = \strlen($this->recvBuffer) === $this->currentPackageLength) {
-                    $one_request_buffer = $this->recvBuffer;
+                    $oneRequestBuffer = $this->recvBuffer;
                     $this->recvBuffer = '';
                 } else {
                     // Get a full package from the buffer.
-                    $one_request_buffer = \substr($this->recvBuffer, 0, $this->currentPackageLength);
+                    $oneRequestBuffer = \substr($this->recvBuffer, 0, $this->currentPackageLength);
                     // Remove the current package from the receive buffer.
                     $this->recvBuffer = \substr($this->recvBuffer, $this->currentPackageLength);
                 }
@@ -665,9 +665,9 @@ class TcpConnection extends ConnectionInterface implements \JsonSerializable
                 $this->currentPackageLength = 0;
                 try {
                     // Decode request buffer before Emitting onMessage callback.
-                    $request = $this->protocol::decode($one_request_buffer, $this);
-                    if (static::$enableCache && (!\is_object($request) || $request instanceof Request) && $one && !isset($one_request_buffer[512])) {
-                        $requests[$one_request_buffer] = $request;
+                    $request = $this->protocol::decode($oneRequestBuffer, $this);
+                    if (static::$enableCache && (!\is_object($request) || $request instanceof Request) && $one && !isset($oneRequestBuffer[512])) {
+                        $requests[$oneRequestBuffer] = $request;
                         if (\count($requests) > 512) {
                             unset($requests[\key($requests)]);
                         }

+ 8 - 8
src/Connection/UdpConnection.php

@@ -52,31 +52,31 @@ class UdpConnection extends ConnectionInterface implements \JsonSerializable
      * Construct.
      *
      * @param resource $socket
-     * @param string $remote_address
+     * @param string $remoteAddress
      */
-    public function __construct($socket, $remote_address)
+    public function __construct($socket, $remoteAddress)
     {
         $this->socket = $socket;
-        $this->remoteAddress = $remote_address;
+        $this->remoteAddress = $remoteAddress;
     }
 
     /**
      * Sends data on the connection.
      *
-     * @param string $send_buffer
+     * @param string $sendBuffer
      * @param bool $raw
      * @return void|boolean
      */
-    public function send($send_buffer, $raw = false)
+    public function send($sendBuffer, $raw = false)
     {
         if (false === $raw && $this->protocol) {
             $parser = $this->protocol;
-            $send_buffer = $parser::encode($send_buffer, $this);
-            if ($send_buffer === '') {
+            $sendBuffer = $parser::encode($sendBuffer, $this);
+            if ($sendBuffer === '') {
                 return;
             }
         }
-        return \strlen($send_buffer) === \stream_socket_sendto($this->socket, $send_buffer, 0, $this->isIpV6() ? '[' . $this->getRemoteIp() . ']:' . $this->getRemotePort() : $this->remoteAddress);
+        return \strlen($sendBuffer) === \stream_socket_sendto($this->socket, $sendBuffer, 0, $this->isIpV6() ? '[' . $this->getRemoteIp() . ']:' . $this->getRemotePort() : $this->remoteAddress);
     }
 
     /**

+ 19 - 19
src/Events/Ev.php

@@ -61,9 +61,9 @@ class Ev implements EventInterface
      */
     public function delay(float $delay, $func, $args)
     {
-        $timer_id = self::$timerId;
-        $event = new \EvTimer($delay, 0, function () use ($func, $args, $timer_id) {
-            unset($this->eventTimer[$timer_id]);
+        $timerId = self::$timerId;
+        $event = new \EvTimer($delay, 0, function () use ($func, $args, $timerId) {
+            unset($this->eventTimer[$timerId]);
             $func(...(array)$args);
         });
         $this->eventTimer[self::$timerId] = $event;
@@ -73,11 +73,11 @@ class Ev implements EventInterface
     /**
      * {@inheritdoc}
      */
-    public function deleteTimer($timer_id)
+    public function deleteTimer($timerId)
     {
-        if (isset($this->eventTimer[$timer_id])) {
-            $this->eventTimer[$timer_id]->stop();
-            unset($this->eventTimer[$timer_id]);
+        if (isset($this->eventTimer[$timerId])) {
+            $this->eventTimer[$timerId]->stop();
+            unset($this->eventTimer[$timerId]);
             return true;
         }
         return false;
@@ -100,11 +100,11 @@ class Ev implements EventInterface
      */
     public function onReadable($stream, $func)
     {
-        $fd_key = (int)$stream;
+        $fdKey = (int)$stream;
         $event = new \EvIo($stream, \Ev::READ, function () use ($func, $stream) {
             $func($stream);
         });
-        $this->readEvents[$fd_key] = $event;
+        $this->readEvents[$fdKey] = $event;
     }
 
     /**
@@ -112,10 +112,10 @@ class Ev implements EventInterface
      */
     public function offReadable($stream)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->readEvents[$fd_key])) {
-            $this->readEvents[$fd_key]->stop();
-            unset($this->readEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->readEvents[$fdKey])) {
+            $this->readEvents[$fdKey]->stop();
+            unset($this->readEvents[$fdKey]);
         }
     }
 
@@ -124,11 +124,11 @@ class Ev implements EventInterface
      */
     public function onWritable($stream, $func)
     {
-        $fd_key = (int)$stream;
+        $fdKey = (int)$stream;
         $event = new \EvIo($stream, \Ev::WRITE, function () use ($func, $stream) {
             $func($stream);
         });
-        $this->readEvents[$fd_key] = $event;
+        $this->readEvents[$fdKey] = $event;
     }
 
     /**
@@ -136,10 +136,10 @@ class Ev implements EventInterface
      */
     public function offWritable($stream)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->writeEvents[$fd_key])) {
-            $this->writeEvents[$fd_key]->stop();
-            unset($this->writeEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->writeEvents[$fdKey])) {
+            $this->writeEvents[$fdKey]->stop();
+            unset($this->writeEvents[$fdKey]);
         }
     }
 

+ 45 - 45
src/Events/Event.php

@@ -71,17 +71,17 @@ class Event implements EventInterface
     public function __construct()
     {
         if (\class_exists('\\\\Event', false)) {
-            $class_name = '\\\\Event';
+            $className = '\\\\Event';
         } else {
-            $class_name = '\Event';
+            $className = '\Event';
         }
-        $this->eventClassName = $class_name;
+        $this->eventClassName = $className;
         if (\class_exists('\\\\EventBase', false)) {
-            $class_name = '\\\\EventBase';
+            $className = '\\\\EventBase';
         } else {
-            $class_name = '\EventBase';
+            $className = '\EventBase';
         }
-        $this->eventBase = new $class_name();
+        $this->eventBase = new $className();
     }
 
     /**
@@ -89,11 +89,11 @@ class Event implements EventInterface
      */
     public function delay(float $delay, $func, $args)
     {
-        $class_name = $this->eventClassName;
-        $timer_id = $this->timerId++;
-        $event = new $class_name($this->eventBase, -1, $class_name::TIMEOUT, function () use ($func, $args, $timer_id) {
+        $className = $this->eventClassName;
+        $timerId = $this->timerId++;
+        $event = new $className($this->eventBase, -1, $className::TIMEOUT, function () use ($func, $args, $timerId) {
             try {
-                $this->deleteTimer($timer_id);
+                $this->deleteTimer($timerId);
                 $func(...$args);
             } catch (\Throwable $e) {
                 Worker::stopAll(250, $e);
@@ -102,18 +102,18 @@ class Event implements EventInterface
         if (!$event || !$event->addTimer($delay)) {
             return false;
         }
-        $this->eventTimer[$timer_id] = $event;
-        return $timer_id;
+        $this->eventTimer[$timerId] = $event;
+        return $timerId;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function deleteTimer($timer_id)
+    public function deleteTimer($timerId)
     {
-        if (isset($this->eventTimer[$timer_id])) {
-            $this->eventTimer[$timer_id]->del();
-            unset($this->eventTimer[$timer_id]);
+        if (isset($this->eventTimer[$timerId])) {
+            $this->eventTimer[$timerId]->del();
+            unset($this->eventTimer[$timerId]);
             return true;
         }
         return false;
@@ -124,9 +124,9 @@ class Event implements EventInterface
      */
     public function repeat(float $interval, $func, $args)
     {
-        $class_name = $this->eventClassName;
-        $timer_id = $this->timerId++;
-        $event = new $class_name($this->eventBase, -1, $class_name::TIMEOUT | $class_name::PERSIST, function () use ($func, $args) {
+        $className = $this->eventClassName;
+        $timerId = $this->timerId++;
+        $event = new $className($this->eventBase, -1, $className::TIMEOUT | $className::PERSIST, function () use ($func, $args) {
             try {
                 $func(...$args);
             } catch (\Throwable $e) {
@@ -136,8 +136,8 @@ class Event implements EventInterface
         if (!$event || !$event->addTimer($interval)) {
             return false;
         }
-        $this->eventTimer[$timer_id] = $event;
-        return $timer_id;
+        $this->eventTimer[$timerId] = $event;
+        return $timerId;
     }
 
     /**
@@ -145,13 +145,13 @@ class Event implements EventInterface
      */
     public function onReadable($stream, $func)
     {
-        $class_name = $this->eventClassName;
-        $fd_key = (int)$stream;
-        $event = new $this->eventClassName($this->eventBase, $stream, $class_name::READ | $class_name::PERSIST, $func, $stream);
+        $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;
         }
-        $this->writeEvents[$fd_key] = $event;
+        $this->writeEvents[$fdKey] = $event;
         return true;
     }
 
@@ -160,10 +160,10 @@ class Event implements EventInterface
      */
     public function offReadable($stream)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->readEvents[$fd_key])) {
-            $this->readEvents[$fd_key]->del();
-            unset($this->readEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->readEvents[$fdKey])) {
+            $this->readEvents[$fdKey]->del();
+            unset($this->readEvents[$fdKey]);
         }
     }
 
@@ -172,13 +172,13 @@ class Event implements EventInterface
      */
     public function onWritable($stream, $func)
     {
-        $class_name = $this->eventClassName;
-        $fd_key = (int)$stream;
-        $event = new $this->eventClassName($this->eventBase, $stream, $class_name::WRITE | $class_name::PERSIST, $func, $stream);
+        $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;
         }
-        $this->writeEvents[$fd_key] = $event;
+        $this->writeEvents[$fdKey] = $event;
         return true;
     }
 
@@ -187,10 +187,10 @@ class Event implements EventInterface
      */
     public function offWritable($stream)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->writeEvents[$fd_key])) {
-            $this->writeEvents[$fd_key]->del();
-            unset($this->writeEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->writeEvents[$fdKey])) {
+            $this->writeEvents[$fdKey]->del();
+            unset($this->writeEvents[$fdKey]);
         }
     }
 
@@ -199,13 +199,13 @@ class Event implements EventInterface
      */
     public function onSignal($signal, $func)
     {
-        $class_name = $this->eventClassName;
-        $fd_key = (int)$signal;
-        $event = $class_name::signal($this->eventBase, $signal, $func);
+        $className = $this->eventClassName;
+        $fdKey = (int)$signal;
+        $event = $className::signal($this->eventBase, $signal, $func);
         if (!$event || !$event->add()) {
             return false;
         }
-        $this->eventSignal[$fd_key] = $event;
+        $this->eventSignal[$fdKey] = $event;
         return true;
     }
 
@@ -214,10 +214,10 @@ class Event implements EventInterface
      */
     public function offSignal($signal)
     {
-        $fd_key = (int)$signal;
-        if (isset($this->eventSignal[$fd_key])) {
-            $this->eventSignal[$fd_key]->del();
-            unset($this->eventSignal[$fd_key]);
+        $fdKey = (int)$signal;
+        if (isset($this->eventSignal[$fdKey])) {
+            $this->eventSignal[$fdKey]->del();
+            unset($this->eventSignal[$fdKey]);
         }
     }
 

+ 2 - 2
src/Events/EventInterface.php

@@ -35,10 +35,10 @@ interface EventInterface
 
     /**
      * Delete a timer.
-     * @param $timer_id
+     * @param $timerId
      * @return bool
      */
-    public function deleteTimer($timer_id);
+    public function deleteTimer($timerId);
 
     /**
      * Execute a callback when a stream resource becomes readable or is closed for reading.

+ 46 - 46
src/Events/Revolt.php

@@ -86,8 +86,8 @@ class Revolt implements EventInterface
      */
     public function stop()
     {
-        foreach ($this->eventSignal as $cb_id) {
-            $this->driver->cancel($cb_id);
+        foreach ($this->eventSignal as $cbId) {
+            $this->driver->cancel($cbId);
         }
         $this->driver->stop();
         pcntl_signal(SIGINT, SIG_IGN);
@@ -99,14 +99,14 @@ class Revolt implements EventInterface
     public function delay(float $delay, $func, $args)
     {
         $args = (array)$args;
-        $timer_id = $this->timerId++;
-        $closure = function () use ($func, $args, $timer_id) {
-            unset($this->eventTimer[$timer_id]);
+        $timerId = $this->timerId++;
+        $closure = function () use ($func, $args, $timerId) {
+            unset($this->eventTimer[$timerId]);
             $func(...$args);
         };
-        $cb_id = $this->driver->delay($delay, $closure);
-        $this->eventTimer[$timer_id] = $cb_id;
-        return $timer_id;
+        $cbId = $this->driver->delay($delay, $closure);
+        $this->eventTimer[$timerId] = $cbId;
+        return $timerId;
     }
 
     /**
@@ -115,13 +115,13 @@ class Revolt implements EventInterface
     public function repeat(float $interval, $func, $args)
     {
         $args = (array)$args;
-        $timer_id = $this->timerId++;
-        $closure = function () use ($func, $args, $timer_id) {
+        $timerId = $this->timerId++;
+        $closure = function () use ($func, $args, $timerId) {
             $func(...$args);
         };
-        $cb_id = $this->driver->repeat($interval, $closure);
-        $this->eventTimer[$timer_id] = $cb_id;
-        return $timer_id;
+        $cbId = $this->driver->repeat($interval, $closure);
+        $this->eventTimer[$timerId] = $cbId;
+        return $timerId;
     }
 
     /**
@@ -129,13 +129,13 @@ class Revolt implements EventInterface
      */
     public function onReadable($stream, $func)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->readEvents[$fd_key])) {
-            $this->driver->cancel($this->readEvents[$fd_key]);
-            unset($this->readEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->readEvents[$fdKey])) {
+            $this->driver->cancel($this->readEvents[$fdKey]);
+            unset($this->readEvents[$fdKey]);
         }
 
-        $this->readEvents[$fd_key] = $this->driver->onReadable($stream, function () use ($stream, $func) {
+        $this->readEvents[$fdKey] = $this->driver->onReadable($stream, function () use ($stream, $func) {
             $func($stream);
         });
     }
@@ -145,10 +145,10 @@ class Revolt implements EventInterface
      */
     public function offReadable($stream)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->readEvents[$fd_key])) {
-            $this->driver->cancel($this->readEvents[$fd_key]);
-            unset($this->readEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->readEvents[$fdKey])) {
+            $this->driver->cancel($this->readEvents[$fdKey]);
+            unset($this->readEvents[$fdKey]);
         }
     }
 
@@ -157,12 +157,12 @@ class Revolt implements EventInterface
      */
     public function onWritable($stream, $func)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->writeEvents[$fd_key])) {
-            $this->driver->cancel($this->writeEvents[$fd_key]);
-            unset($this->writeEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->writeEvents[$fdKey])) {
+            $this->driver->cancel($this->writeEvents[$fdKey]);
+            unset($this->writeEvents[$fdKey]);
         }
-        $this->writeEvents[$fd_key] = $this->driver->onWritable($stream, function () use ($stream, $func) {
+        $this->writeEvents[$fdKey] = $this->driver->onWritable($stream, function () use ($stream, $func) {
             $func($stream);
         });
     }
@@ -172,10 +172,10 @@ class Revolt implements EventInterface
      */
     public function offWritable($stream)
     {
-        $fd_key = (int)$stream;
-        if (isset($this->writeEvents[$fd_key])) {
-            $this->driver->cancel($this->writeEvents[$fd_key]);
-            unset($this->writeEvents[$fd_key]);
+        $fdKey = (int)$stream;
+        if (isset($this->writeEvents[$fdKey])) {
+            $this->driver->cancel($this->writeEvents[$fdKey]);
+            unset($this->writeEvents[$fdKey]);
         }
     }
 
@@ -184,12 +184,12 @@ class Revolt implements EventInterface
      */
     public function onSignal($signal, $func)
     {
-        $fd_key = (int)$signal;
-        if (isset($this->eventSignal[$fd_key])) {
-            $this->driver->cancel($this->eventSignal[$fd_key]);
-            unset($this->eventSignal[$fd_key]);
+        $fdKey = (int)$signal;
+        if (isset($this->eventSignal[$fdKey])) {
+            $this->driver->cancel($this->eventSignal[$fdKey]);
+            unset($this->eventSignal[$fdKey]);
         }
-        $this->eventSignal[$fd_key] = $this->driver->onSignal($signal, function () use ($signal, $func) {
+        $this->eventSignal[$fdKey] = $this->driver->onSignal($signal, function () use ($signal, $func) {
             $func($signal);
         });
     }
@@ -199,21 +199,21 @@ class Revolt implements EventInterface
      */
     public function offSignal($signal)
     {
-        $fd_key = (int)$signal;
-        if (isset($this->eventSignal[$fd_key])) {
-            $this->driver->cancel($this->eventSignal[$fd_key]);
-            unset($this->eventSignal[$fd_key]);
+        $fdKey = (int)$signal;
+        if (isset($this->eventSignal[$fdKey])) {
+            $this->driver->cancel($this->eventSignal[$fdKey]);
+            unset($this->eventSignal[$fdKey]);
         }
     }
 
     /**
      * {@inheritdoc}
      */
-    public function deleteTimer($timer_id)
+    public function deleteTimer($timerId)
     {
-        if (isset($this->eventTimer[$timer_id])) {
-            $this->driver->cancel($this->eventTimer[$timer_id]);
-            unset($this->eventTimer[$timer_id]);
+        if (isset($this->eventTimer[$timerId])) {
+            $this->driver->cancel($this->eventTimer[$timerId]);
+            unset($this->eventTimer[$timerId]);
             return true;
         }
         return false;
@@ -224,8 +224,8 @@ class Revolt implements EventInterface
      */
     public function deleteAllTimer()
     {
-        foreach ($this->eventTimer as $cb_id) {
-            $this->driver->cancel($cb_id);
+        foreach ($this->eventTimer as $cbId) {
+            $this->driver->cancel($cbId);
         }
         $this->eventTimer = [];
     }

+ 63 - 63
src/Events/Select.php

@@ -114,16 +114,16 @@ class Select implements EventInterface
      */
     public function delay(float $delay, $func, $args)
     {
-        $timer_id = $this->timerId++;
-        $run_time = \microtime(true) + $delay;
-        $this->scheduler->insert($timer_id, -$run_time);
-        $this->eventTimer[$timer_id] = [$func, (array)$args];
-        $select_timeout = ($run_time - \microtime(true)) * 1000000;
-        $select_timeout = $select_timeout <= 0 ? 1 : (int)$select_timeout;
-        if ($this->selectTimeout > $select_timeout) {
-            $this->selectTimeout = $select_timeout;
+        $timerId = $this->timerId++;
+        $runTime = \microtime(true) + $delay;
+        $this->scheduler->insert($timerId, -$runTime);
+        $this->eventTimer[$timerId] = [$func, (array)$args];
+        $selectTimeout = ($runTime - \microtime(true)) * 1000000;
+        $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
+        if ($this->selectTimeout > $selectTimeout) {
+            $this->selectTimeout = $selectTimeout;
         }
-        return $timer_id;
+        return $timerId;
     }
 
     /**
@@ -131,25 +131,25 @@ class Select implements EventInterface
      */
     public function repeat(float $delay, $func, $args)
     {
-        $timer_id = $this->timerId++;
-        $run_time = \microtime(true) + $delay;
-        $this->scheduler->insert($timer_id, -$run_time);
-        $this->eventTimer[$timer_id] = [$func, (array)$args, $delay];
-        $select_timeout = ($run_time - \microtime(true)) * 1000000;
-        $select_timeout = $select_timeout <= 0 ? 1 : (int)$select_timeout;
-        if ($this->selectTimeout > $select_timeout) {
-            $this->selectTimeout = $select_timeout;
+        $timerId = $this->timerId++;
+        $runTime = \microtime(true) + $delay;
+        $this->scheduler->insert($timerId, -$runTime);
+        $this->eventTimer[$timerId] = [$func, (array)$args, $delay];
+        $selectTimeout = ($runTime - \microtime(true)) * 1000000;
+        $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
+        if ($this->selectTimeout > $selectTimeout) {
+            $this->selectTimeout = $selectTimeout;
         }
-        return $timer_id;
+        return $timerId;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function deleteTimer($timer_id)
+    public function deleteTimer($timerId)
     {
-        if (isset($this->eventTimer[$timer_id])) {
-            unset($this->eventTimer[$timer_id]);
+        if (isset($this->eventTimer[$timerId])) {
+            unset($this->eventTimer[$timerId]);
             return true;
         }
         return false;
@@ -166,9 +166,9 @@ class Select implements EventInterface
         } else if (\DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
             echo "Warning: system call select exceeded the maximum number of connections 256.\n";
         }
-        $fd_key = (int)$stream;
-        $this->readEvents[$fd_key] = $func;
-        $this->readFds[$fd_key] = $stream;
+        $fdKey = (int)$stream;
+        $this->readEvents[$fdKey] = $func;
+        $this->readFds[$fdKey] = $stream;
     }
 
     /**
@@ -176,8 +176,8 @@ class Select implements EventInterface
      */
     public function offReadable($stream)
     {
-        $fd_key = (int)$stream;
-        unset($this->readEvents[$fd_key], $this->readFds[$fd_key]);
+        $fdKey = (int)$stream;
+        unset($this->readEvents[$fdKey], $this->readFds[$fdKey]);
     }
 
     /**
@@ -191,9 +191,9 @@ class Select implements EventInterface
         } else if (\DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
             echo "Warning: system call select exceeded the maximum number of connections 256.\n";
         }
-        $fd_key = (int)$stream;
-        $this->writeEvents[$fd_key] = $func;
-        $this->writeFds[$fd_key] = $stream;
+        $fdKey = (int)$stream;
+        $this->writeEvents[$fdKey] = $func;
+        $this->writeFds[$fdKey] = $stream;
     }
 
     /**
@@ -201,8 +201,8 @@ class Select implements EventInterface
      */
     public function offWritable($stream)
     {
-        $fd_key = (int)$stream;
-        unset($this->writeEvents[$fd_key], $this->writeFds[$fd_key]);
+        $fdKey = (int)$stream;
+        unset($this->writeEvents[$fdKey], $this->writeFds[$fdKey]);
     }
 
     /**
@@ -210,9 +210,9 @@ class Select implements EventInterface
      */
     public function onExcept($stream, $func)
     {
-        $fd_key = (int)$stream;
-        $this->exceptEvents[$fd_key] = $func;
-        $this->exceptFds[$fd_key] = $stream;
+        $fdKey = (int)$stream;
+        $this->exceptEvents[$fdKey] = $func;
+        $this->exceptFds[$fdKey] = $stream;
     }
 
     /**
@@ -220,8 +220,8 @@ class Select implements EventInterface
      */
     public function offExcept($stream)
     {
-        $fd_key = (int)$stream;
-        unset($this->exceptEvents[$fd_key], $this->exceptFds[$fd_key]);
+        $fdKey = (int)$stream;
+        unset($this->exceptEvents[$fdKey], $this->exceptFds[$fdKey]);
     }
 
     /**
@@ -262,30 +262,30 @@ class Select implements EventInterface
      */
     protected function tick()
     {
-        $tasks_to_insert = [];
+        $tasksToInsert = [];
         while (!$this->scheduler->isEmpty()) {
-            $scheduler_data = $this->scheduler->top();
-            $timer_id = $scheduler_data['data'];
-            $next_run_time = -$scheduler_data['priority'];
-            $time_now = \microtime(true);
-            $this->selectTimeout = (int)(($next_run_time - $time_now) * 1000000);
+            $schedulerData = $this->scheduler->top();
+            $timerId = $schedulerData['data'];
+            $nextRunTime = -$schedulerData['priority'];
+            $timeNow = \microtime(true);
+            $this->selectTimeout = (int)(($nextRunTime - $timeNow) * 1000000);
             if ($this->selectTimeout <= 0) {
                 $this->scheduler->extract();
 
-                if (!isset($this->eventTimer[$timer_id])) {
+                if (!isset($this->eventTimer[$timerId])) {
                     continue;
                 }
 
                 // [func, args, timer_interval]
-                $task_data = $this->eventTimer[$timer_id];
-                if (isset($task_data[2])) {
-                    $next_run_time = $time_now + $task_data[2];
-                    $tasks_to_insert[] = [$timer_id, -$next_run_time];
+                $taskData = $this->eventTimer[$timerId];
+                if (isset($taskData[2])) {
+                    $nextRunTime = $timeNow + $taskData[2];
+                    $tasksToInsert[] = [$timerId, -$nextRunTime];
                 } else {
-                    unset($this->eventTimer[$timer_id]);
+                    unset($this->eventTimer[$timerId]);
                 }
                 try {
-                    $task_data[0]($task_data[1]);
+                    $taskData[0]($taskData[1]);
                 } catch (Throwable $e) {
                     Worker::stopAll(250, $e);
                 }
@@ -293,14 +293,14 @@ class Select implements EventInterface
                 break;
             }
         }
-        foreach ($tasks_to_insert as $item) {
+        foreach ($tasksToInsert as $item) {
             $this->scheduler->insert($item[0], $item[1]);
         }
         if (!$this->scheduler->isEmpty()) {
-            $scheduler_data = $this->scheduler->top();
-            $next_run_time = -$scheduler_data['priority'];
-            $time_now = \microtime(true);
-            $this->selectTimeout = \max((int)(($next_run_time - $time_now) * 1000000), 0);
+            $schedulerData = $this->scheduler->top();
+            $nextRunTime = -$schedulerData['priority'];
+            $timeNow = \microtime(true);
+            $this->selectTimeout = \max((int)(($nextRunTime - $timeNow) * 1000000), 0);
             return;
         }
         $this->selectTimeout = 100000000;
@@ -347,23 +347,23 @@ class Select implements EventInterface
             }
 
             foreach ($read as $fd) {
-                $fd_key = (int)$fd;
-                if (isset($this->readEvents[$fd_key])) {
-                    $this->readEvents[$fd_key]($fd);
+                $fdKey = (int)$fd;
+                if (isset($this->readEvents[$fdKey])) {
+                    $this->readEvents[$fdKey]($fd);
                 }
             }
 
             foreach ($write as $fd) {
-                $fd_key = (int)$fd;
-                if (isset($this->writeEvents[$fd_key])) {
-                    $this->writeEvents[$fd_key]($fd);
+                $fdKey = (int)$fd;
+                if (isset($this->writeEvents[$fdKey])) {
+                    $this->writeEvents[$fdKey]($fd);
                 }
             }
 
             foreach ($except as $fd) {
-                $fd_key = (int)$fd;
-                if (isset($this->exceptEvents[$fd_key])) {
-                    $this->exceptEvents[$fd_key]($fd);
+                $fdKey = (int)$fd;
+                if (isset($this->exceptEvents[$fdKey])) {
+                    $this->exceptEvents[$fdKey]($fd);
                 }
             }
         }

+ 13 - 13
src/Events/Swoole.php

@@ -45,26 +45,26 @@ class Swoole implements EventInterface
     {
         $t = (int)($delay * 1000);
         $t = $t < 1 ? 1 : $t;
-        $timer_id = Timer::after($t, function () use ($func, $args, &$timer_id) {
-            unset($this->eventTimer[$timer_id]);
+        $timerId = Timer::after($t, function () use ($func, $args, &$timerId) {
+            unset($this->eventTimer[$timerId]);
             try {
                 $func(...(array)$args);
             } catch (\Throwable $e) {
                 Worker::stopAll(250, $e);
             }
         });
-        $this->eventTimer[$timer_id] = $timer_id;
-        return $timer_id;
+        $this->eventTimer[$timerId] = $timerId;
+        return $timerId;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function deleteTimer($timer_id)
+    public function deleteTimer($timerId)
     {
-        if (isset($this->eventTimer[$timer_id])) {
-            $res = Timer::clear($timer_id);
-            unset($this->eventTimer[$timer_id]);
+        if (isset($this->eventTimer[$timerId])) {
+            $res = Timer::clear($timerId);
+            unset($this->eventTimer[$timerId]);
             return $res;
         }
         return false;
@@ -80,15 +80,15 @@ class Swoole implements EventInterface
         }
         $t = (int)($interval * 1000);
         $t = $t < 1 ? 1 : $t;
-        $timer_id = Timer::tick($t, function () use ($func, $args) {
+        $timerId = Timer::tick($t, function () use ($func, $args) {
             try {
                 $func(...(array)$args);
             } catch (\Throwable $e) {
                 Worker::stopAll(250, $e);
             }
         });
-        $this->eventTimer[$timer_id] = $timer_id;
-        return $timer_id;
+        $this->eventTimer[$timerId] = $timerId;
+        return $timerId;
     }
 
     /**
@@ -163,8 +163,8 @@ class Swoole implements EventInterface
      */
     public function deleteAllTimer()
     {
-        foreach ($this->eventTimer as $timer_id) {
-            Timer::clear($timer_id);
+        foreach ($this->eventTimer as $timerId) {
+            Timer::clear($timerId);
         }
     }
 

+ 12 - 12
src/Events/Swow.php

@@ -69,9 +69,9 @@ class Swow implements EventInterface
                 Worker::stopAll(250, $e);
             }
         });
-        $timer_id = $coroutine->getId();
-        $this->eventTimer[$timer_id] = $timer_id;
-        return $timer_id;
+        $timerId = $coroutine->getId();
+        $this->eventTimer[$timerId] = $timerId;
+        return $timerId;
     }
 
     /**
@@ -91,22 +91,22 @@ class Swow implements EventInterface
                 }
             }
         });
-        $timer_id = $coroutine->getId();
-        $this->eventTimer[$timer_id] = $timer_id;
-        return $timer_id;
+        $timerId = $coroutine->getId();
+        $this->eventTimer[$timerId] = $timerId;
+        return $timerId;
     }
 
     /**
      * {@inheritdoc}
      */
-    public function deleteTimer($timer_id)
+    public function deleteTimer($timerId)
     {
-        if (isset($this->eventTimer[$timer_id])) {
+        if (isset($this->eventTimer[$timerId])) {
             try {
-                (Coroutine::getAll()[$timer_id])->kill();
+                (Coroutine::getAll()[$timerId])->kill();
                 return true;
             } finally {
-                unset($this->eventTimer[$timer_id]);
+                unset($this->eventTimer[$timerId]);
             }
         }
         return false;
@@ -117,8 +117,8 @@ class Swow implements EventInterface
      */
     public function deleteAllTimer()
     {
-        foreach ($this->eventTimer as $timer_id) {
-            $this->deleteTimer($timer_id);
+        foreach ($this->eventTimer as $timerId) {
+            $this->deleteTimer($timerId);
         }
     }
 

+ 4 - 4
src/Protocols/Frame.php

@@ -33,8 +33,8 @@ class Frame
         if (\strlen($buffer) < 4) {
             return 0;
         }
-        $unpack_data = \unpack('Ntotal_length', $buffer);
-        return $unpack_data['total_length'];
+        $unpackData = \unpack('Ntotal_length', $buffer);
+        return $unpackData['total_length'];
     }
 
     /**
@@ -56,7 +56,7 @@ class Frame
      */
     public static function encode($buffer)
     {
-        $total_length = 4 + \strlen($buffer);
-        return \pack('N', $total_length) . $buffer;
+        $totalLength = 4 + \strlen($buffer);
+        return \pack('N', $totalLength) . $buffer;
     }
 }

+ 51 - 51
src/Protocols/Http.php

@@ -48,13 +48,13 @@ class Http
     /**
      * Get or set the request class name.
      *
-     * @param string|null $class_name
+     * @param string|null $className
      * @return string
      */
-    public static function requestClass($class_name = null)
+    public static function requestClass($className = null)
     {
-        if ($class_name) {
-            static::$requestClass = $class_name;
+        if ($className) {
+            static::$requestClass = $className;
         }
         return static::$requestClass;
     }
@@ -72,35 +72,35 @@ class Http
     /**
      * Check the integrity of the package.
      *
-     * @param string $recv_buffer
+     * @param string $recvBuffer
      * @param TcpConnection $connection
      * @return int
      */
-    public static function input(string $recv_buffer, TcpConnection $connection)
+    public static function input(string $recvBuffer, TcpConnection $connection)
     {
         static $input = [];
-        if (!isset($recv_buffer[512]) && isset($input[$recv_buffer])) {
-            return $input[$recv_buffer];
+        if (!isset($recvBuffer[512]) && isset($input[$recvBuffer])) {
+            return $input[$recvBuffer];
         }
-        $crlf_pos = \strpos($recv_buffer, "\r\n\r\n");
-        if (false === $crlf_pos) {
+        $crlfPos = \strpos($recvBuffer, "\r\n\r\n");
+        if (false === $crlfPos) {
             // Judge whether the package length exceeds the limit.
-            if (\strlen($recv_buffer) >= 16384) {
+            if (\strlen($recvBuffer) >= 16384) {
                 $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
                 return 0;
             }
             return 0;
         }
 
-        $length = $crlf_pos + 4;
-        $firstLine = \explode(" ", \strstr($recv_buffer, "\r\n", true), 3);
+        $length = $crlfPos + 4;
+        $firstLine = \explode(" ", \strstr($recvBuffer, "\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($recv_buffer, 0, $crlf_pos);
+        $header = \substr($recvBuffer, 0, $crlfPos);
         $hostHeaderPosition = \strpos($header, "\r\nHost: ");
 
         if (false === $hostHeaderPosition && $firstLine[2] === "HTTP/1.1") {
@@ -110,27 +110,27 @@ class Http
 
         if ($pos = \strpos($header, "\r\nContent-Length: ")) {
             $length = $length + (int)\substr($header, $pos + 18, 10);
-            $has_content_length = true;
+            $hasContentLength = true;
         } else if (\preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) {
             $length = $length + $match[1];
-            $has_content_length = true;
+            $hasContentLength = true;
         } else {
-            $has_content_length = false;
+            $hasContentLength = false;
             if (false !== stripos($header, "\r\nTransfer-Encoding:")) {
                 $connection->close("HTTP/1.1 400 Bad Request\r\n\r\n", true);
                 return 0;
             }
         }
 
-        if ($has_content_length) {
+        if ($hasContentLength) {
             if ($length > $connection->maxPackageSize) {
                 $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
                 return 0;
             }
         }
 
-        if (!isset($recv_buffer[512])) {
-            $input[$recv_buffer] = $length;
+        if (!isset($recvBuffer[512])) {
+            $input[$recvBuffer] = $length;
             if (\count($input) > 512) {
                 unset($input[key($input)]);
             }
@@ -142,26 +142,26 @@ class Http
     /**
      * Http decode.
      *
-     * @param string $recv_buffer
+     * @param string $recvBuffer
      * @param TcpConnection $connection
      * @return \Workerman\Protocols\Http\Request
      */
-    public static function decode($recv_buffer, TcpConnection $connection)
+    public static function decode($recvBuffer, TcpConnection $connection)
     {
         static $requests = [];
-        $cacheable = static::$enableCache && !isset($recv_buffer[512]);
-        if (true === $cacheable && isset($requests[$recv_buffer])) {
-            $request = clone $requests[$recv_buffer];
+        $cacheable = static::$enableCache && !isset($recvBuffer[512]);
+        if (true === $cacheable && isset($requests[$recvBuffer])) {
+            $request = clone $requests[$recvBuffer];
             $request->connection = $connection;
             $connection->request = $request;
             $request->properties = [];
             return $request;
         }
-        $request = new static::$requestClass($recv_buffer);
+        $request = new static::$requestClass($recvBuffer);
         $request->connection = $connection;
         $connection->request = $request;
         if (true === $cacheable) {
-            $requests[$recv_buffer] = $request;
+            $requests[$recvBuffer] = $request;
             if (\count($requests) > 512) {
                 unset($requests[\key($requests)]);
             }
@@ -184,21 +184,21 @@ class Http
             $connection->request = null;
         }
         if (!\is_object($response)) {
-            $ext_header = '';
+            $extHeader = '';
             if (isset($connection->header)) {
                 foreach ($connection->header as $name => $value) {
                     if (\is_array($value)) {
                         foreach ($value as $item) {
-                            $ext_header = "$name: $item\r\n";
+                            $extHeader = "$name: $item\r\n";
                         }
                     } else {
-                        $ext_header = "$name: $value\r\n";
+                        $extHeader = "$name: $value\r\n";
                     }
                 }
                 unset($connection->header);
             }
-            $body_len = \strlen((string)$response);
-            return "HTTP/1.1 200 OK\r\nServer: workerman\r\n{$ext_header}Connection: keep-alive\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $body_len\r\n\r\n$response";
+            $bodyLen = \strlen((string)$response);
+            return "HTTP/1.1 200 OK\r\nServer: workerman\r\n{$extHeader}Connection: keep-alive\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $bodyLen\r\n\r\n$response";
         }
 
         if (isset($connection->header)) {
@@ -211,18 +211,18 @@ class Http
             $offset = $response->file['offset'];
             $length = $response->file['length'];
             \clearstatcache();
-            $file_size = (int)\filesize($file);
-            $body_len = $length > 0 ? $length : $file_size - $offset;
+            $fileSize = (int)\filesize($file);
+            $bodyLen = $length > 0 ? $length : $fileSize - $offset;
             $response->withHeaders([
-                'Content-Length' => $body_len,
+                'Content-Length' => $bodyLen,
                 'Accept-Ranges' => 'bytes',
             ]);
             if ($offset || $length) {
-                $offset_end = $offset + $body_len - 1;
-                $response->header('Content-Range', "bytes $offset-$offset_end/$file_size");
+                $offsetEnd = $offset + $bodyLen - 1;
+                $response->header('Content-Range', "bytes $offset-$offsetEnd/$fileSize");
             }
-            if ($body_len < 2 * 1024 * 1024) {
-                $connection->send((string)$response . file_get_contents($file, false, null, $offset, $body_len), true);
+            if ($bodyLen < 2 * 1024 * 1024) {
+                $connection->send((string)$response . file_get_contents($file, false, null, $offset, $bodyLen), true);
                 return '';
             }
             $handler = \fopen($file, 'r');
@@ -253,22 +253,22 @@ class Http
         if ($offset !== 0) {
             \fseek($handler, $offset);
         }
-        $offset_end = $offset + $length;
+        $offsetEnd = $offset + $length;
         // Read file content from disk piece by piece and send to client.
-        $do_write = function () use ($connection, $handler, $length, $offset_end) {
+        $doWrite = function () use ($connection, $handler, $length, $offsetEnd) {
             // Send buffer not full.
             while ($connection->bufferFull === false) {
                 // Read from disk.
                 $size = 1024 * 1024;
                 if ($length !== 0) {
                     $tell = \ftell($handler);
-                    $remain_size = $offset_end - $tell;
-                    if ($remain_size <= 0) {
+                    $remainSize = $offsetEnd - $tell;
+                    if ($remainSize <= 0) {
                         fclose($handler);
                         $connection->onBufferDrain = null;
                         return;
                     }
-                    $size = $remain_size > $size ? $size : $remain_size;
+                    $size = $remainSize > $size ? $size : $remainSize;
                 }
 
                 $buffer = \fread($handler, $size);
@@ -287,11 +287,11 @@ class Http
             $connection->bufferFull = true;
         };
         // Send buffer drain.
-        $connection->onBufferDrain = function ($connection) use ($do_write) {
+        $connection->onBufferDrain = function ($connection) use ($doWrite) {
             $connection->bufferFull = false;
-            $do_write();
+            $doWrite();
         };
-        $do_write();
+        $doWrite();
     }
 
     /**
@@ -305,10 +305,10 @@ class Http
             static::$uploadTmpDir = $dir;
         }
         if (static::$uploadTmpDir === '') {
-            if ($upload_tmp_dir = \ini_get('upload_tmp_dir')) {
-                static::$uploadTmpDir = $upload_tmp_dir;
-            } else if ($upload_tmp_dir = \sys_get_temp_dir()) {
-                static::$uploadTmpDir = $upload_tmp_dir;
+            if ($uploadTmpDir = \ini_get('upload_tmp_dir')) {
+                static::$uploadTmpDir = $uploadTmpDir;
+            } else if ($uploadTmpDir = \sys_get_temp_dir()) {
+                static::$uploadTmpDir = $uploadTmpDir;
             }
         }
         return static::$uploadTmpDir;

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

@@ -203,13 +203,13 @@ class Request
     /**
      * Get host.
      *
-     * @param bool $without_port
+     * @param bool $withoutPort
      * @return string
      */
-    public function host($without_port = false)
+    public function host($withoutPort = false)
     {
         $host = $this->header('host');
-        if ($host && $without_port && $pos = \strpos($host, ':')) {
+        if ($host && $withoutPort && $pos = \strpos($host, ':')) {
             return \substr($host, 0, $pos);
         }
         return $host;
@@ -262,11 +262,11 @@ class Request
     public function session()
     {
         if ($this->session === null) {
-            $session_id = $this->sessionId();
-            if ($session_id === false) {
+            $sessionId = $this->sessionId();
+            if ($sessionId === false) {
                 return false;
             }
-            $this->session = new Session($session_id);
+            $this->session = new Session($sessionId);
         }
         return $this->session;
     }
@@ -274,25 +274,25 @@ class Request
     /**
      * Get/Set session id.
      *
-     * @param $session_id
+     * @param $sessionId
      * @return string
      */
-    public function sessionId($session_id = null)
+    public function sessionId($sessionId = null)
     {
-        if ($session_id) {
+        if ($sessionId) {
             unset($this->sid);
         }
         if (!isset($this->sid)) {
-            $session_name = Session::$name;
-            $sid = $session_id ? '' : $this->cookie($session_name);
+            $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;
                 }
-                $sid = $session_id ?: static::createSessionId();
-                $cookie_params = Session::getCookieParams();
-                $this->setSidCookie($session_name, $sid, $cookie_params);
+                $sid = $sessionId ?: static::createSessionId();
+                $cookieParams = Session::getCookieParams();
+                $this->setSidCookie($sessionName, $sid, $cookieParams);
             }
             $this->sid = $sid;
         }
@@ -301,22 +301,22 @@ class Request
 
     /**
      * Session regenerate id
-     * @param bool $delete_old_session
+     * @param bool $deleteOldSession
      * @return void
      */
-    public function sessionRegenerateId($delete_old_session = false)
+    public function sessionRegenerateId($deleteOldSession = false)
     {
         $session = $this->session();
-        $session_data = $session->all();
-        if ($delete_old_session) {
+        $sessionData = $session->all();
+        if ($deleteOldSession) {
             $session->flush();
         }
-        $new_sid = static::createSessionId();
-        $session = new Session($new_sid);
-        $session->put($session_data);
-        $cookie_params = Session::getCookieParams();
-        $session_name = Session::$name;
-        $this->setSidCookie($session_name, $new_sid, $cookie_params);
+        $newSid = static::createSessionId();
+        $session = new Session($newSid);
+        $session->put($sessionData);
+        $cookieParams = Session::getCookieParams();
+        $sessionName = Session::$name;
+        $this->setSidCookie($sessionName, $newSid, $cookieParams);
     }
 
     /**
@@ -369,8 +369,8 @@ class Request
      */
     protected function parseHeadFirstLine()
     {
-        $first_line = \strstr($this->buffer, "\r\n", true);
-        $tmp = \explode(' ', $first_line, 3);
+        $firstLine = \strstr($this->buffer, "\r\n", true);
+        $tmp = \explode(' ', $firstLine, 3);
         $this->data['method'] = $tmp[0];
         $this->data['uri'] = $tmp[1] ?? '/';
     }
@@ -382,9 +382,9 @@ class Request
      */
     protected function parseProtocolVersion()
     {
-        $first_line = \strstr($this->buffer, "\r\n", true);
-        $protoco_version = substr(\strstr($first_line, 'HTTP/'), 5);
-        $this->data['protocolVersion'] = $protoco_version ? $protoco_version : '1.0';
+        $firstLine = \strstr($this->buffer, "\r\n", true);
+        $protocoVersion = substr(\strstr($firstLine, 'HTTP/'), 5);
+        $this->data['protocolVersion'] = $protocoVersion ? $protocoVersion : '1.0';
     }
 
     /**
@@ -396,19 +396,19 @@ class Request
     {
         static $cache = [];
         $this->data['headers'] = [];
-        $raw_head = $this->rawHead();
-        $end_line_position = \strpos($raw_head, "\r\n");
-        if ($end_line_position === false) {
+        $rawHead = $this->rawHead();
+        $endLinePosition = \strpos($rawHead, "\r\n");
+        if ($endLinePosition === false) {
             return;
         }
-        $head_buffer = \substr($raw_head, $end_line_position + 2);
-        $cacheable = static::$enableCache && !isset($head_buffer[2048]);
-        if ($cacheable && isset($cache[$head_buffer])) {
-            $this->data['headers'] = $cache[$head_buffer];
+        $headBuffer = \substr($rawHead, $endLinePosition + 2);
+        $cacheable = static::$enableCache && !isset($headBuffer[2048]);
+        if ($cacheable && isset($cache[$headBuffer])) {
+            $this->data['headers'] = $cache[$headBuffer];
             return;
         }
-        $head_data = \explode("\r\n", $head_buffer);
-        foreach ($head_data as $content) {
+        $headData = \explode("\r\n", $headBuffer);
+        foreach ($headData as $content) {
             if (false !== \strpos($content, ':')) {
                 list($key, $value) = \explode(':', $content, 2);
                 $key = \strtolower($key);
@@ -424,7 +424,7 @@ class Request
             }
         }
         if ($cacheable) {
-            $cache[$head_buffer] = $this->data['headers'];
+            $cache[$headBuffer] = $this->data['headers'];
             if (\count($cache) > 128) {
                 unset($cache[key($cache)]);
             }
@@ -439,19 +439,19 @@ class Request
     protected function parseGet()
     {
         static $cache = [];
-        $query_string = $this->queryString();
+        $queryString = $this->queryString();
         $this->data['get'] = [];
-        if ($query_string === '') {
+        if ($queryString === '') {
             return;
         }
-        $cacheable = static::$enableCache && !isset($query_string[1024]);
-        if ($cacheable && isset($cache[$query_string])) {
-            $this->data['get'] = $cache[$query_string];
+        $cacheable = static::$enableCache && !isset($queryString[1024]);
+        if ($cacheable && isset($cache[$queryString])) {
+            $this->data['get'] = $cache[$queryString];
             return;
         }
-        \parse_str($query_string, $this->data['get']);
+        \parse_str($queryString, $this->data['get']);
         if ($cacheable) {
-            $cache[$query_string] = $this->data['get'];
+            $cache[$queryString] = $this->data['get'];
             if (\count($cache) > 256) {
                 unset($cache[key($cache)]);
             }
@@ -467,28 +467,28 @@ class Request
     {
         static $cache = [];
         $this->data['post'] = $this->data['files'] = [];
-        $content_type = $this->header('content-type', '');
-        if (\preg_match('/boundary="?(\S+)"?/', $content_type, $match)) {
-            $http_post_boundary = '--' . $match[1];
-            $this->parseUploadFiles($http_post_boundary);
+        $contentType = $this->header('content-type', '');
+        if (\preg_match('/boundary="?(\S+)"?/', $contentType, $match)) {
+            $httpPostBoundary = '--' . $match[1];
+            $this->parseUploadFiles($httpPostBoundary);
             return;
         }
-        $body_buffer = $this->rawBody();
-        if ($body_buffer === '') {
+        $bodyBuffer = $this->rawBody();
+        if ($bodyBuffer === '') {
             return;
         }
-        $cacheable = static::$enableCache && !isset($body_buffer[1024]);
-        if ($cacheable && isset($cache[$body_buffer])) {
-            $this->data['post'] = $cache[$body_buffer];
+        $cacheable = static::$enableCache && !isset($bodyBuffer[1024]);
+        if ($cacheable && isset($cache[$bodyBuffer])) {
+            $this->data['post'] = $cache[$bodyBuffer];
             return;
         }
-        if (\preg_match('/\bjson\b/i', $content_type)) {
-            $this->data['post'] = (array)\json_decode($body_buffer, true);
+        if (\preg_match('/\bjson\b/i', $contentType)) {
+            $this->data['post'] = (array)\json_decode($bodyBuffer, true);
         } else {
-            \parse_str($body_buffer, $this->data['post']);
+            \parse_str($bodyBuffer, $this->data['post']);
         }
         if ($cacheable) {
-            $cache[$body_buffer] = $this->data['post'];
+            $cache[$bodyBuffer] = $this->data['post'];
             if (\count($cache) > 256) {
                 unset($cache[key($cache)]);
             }
@@ -498,28 +498,28 @@ class Request
     /**
      * Parse upload files.
      *
-     * @param string $http_post_boundary
+     * @param string $httpPostBoundary
      * @return void
      */
-    protected function parseUploadFiles($http_post_boundary)
+    protected function parseUploadFiles($httpPostBoundary)
     {
-        $http_post_boundary = \trim($http_post_boundary, '"');
+        $httpPostBoundary = \trim($httpPostBoundary, '"');
         $buffer = $this->buffer;
-        $post_encode_string = '';
-        $files_encode_string = '';
+        $postEncodeString = '';
+        $filesEncodeString = '';
         $files = [];
-        $boday_position = strpos($buffer, "\r\n\r\n") + 4;
-        $offset = $boday_position + strlen($http_post_boundary) + 2;
-        $max_count = static::$maxFileUploads;
-        while ($max_count-- > 0 && $offset) {
-            $offset = $this->parseUploadFile($http_post_boundary, $offset, $post_encode_string, $files_encode_string, $files);
+        $bodayPosition = strpos($buffer, "\r\n\r\n") + 4;
+        $offset = $bodayPosition + strlen($httpPostBoundary) + 2;
+        $maxCount = static::$maxFileUploads;
+        while ($maxCount-- > 0 && $offset) {
+            $offset = $this->parseUploadFile($httpPostBoundary, $offset, $postEncodeString, $filesEncodeString, $files);
         }
-        if ($post_encode_string) {
-            parse_str($post_encode_string, $this->data['post']);
+        if ($postEncodeString) {
+            parse_str($postEncodeString, $this->data['post']);
         }
 
-        if ($files_encode_string) {
-            parse_str($files_encode_string, $this->data['files']);
+        if ($filesEncodeString) {
+            parse_str($filesEncodeString, $this->data['files']);
             \array_walk_recursive($this->data['files'], function (&$value) use ($files) {
                 $value = $files[$value];
             });
@@ -528,56 +528,56 @@ class Request
 
     /**
      * @param $boundary
-     * @param $section_start_offset
+     * @param $sectionStartOffset
      * @return int
      */
-    protected function parseUploadFile($boundary, $section_start_offset, &$post_encode_string, &$files_encode_str, &$files)
+    protected function parseUploadFile($boundary, $sectionStartOffset, &$postEncodeString, &$filesEncodeStr, &$files)
     {
         $file = [];
         $boundary = "\r\n$boundary";
-        if (\strlen($this->buffer) < $section_start_offset) {
+        if (\strlen($this->buffer) < $sectionStartOffset) {
             return 0;
         }
-        $section_end_offset = \strpos($this->buffer, $boundary, $section_start_offset);
-        if (!$section_end_offset) {
+        $sectionEndOffset = \strpos($this->buffer, $boundary, $sectionStartOffset);
+        if (!$sectionEndOffset) {
             return 0;
         }
-        $content_lines_end_offset = \strpos($this->buffer, "\r\n\r\n", $section_start_offset);
-        if (!$content_lines_end_offset || $content_lines_end_offset + 4 > $section_end_offset) {
+        $contentLinesEndOffset = \strpos($this->buffer, "\r\n\r\n", $sectionStartOffset);
+        if (!$contentLinesEndOffset || $contentLinesEndOffset + 4 > $sectionEndOffset) {
             return 0;
         }
-        $content_lines_str = \substr($this->buffer, $section_start_offset, $content_lines_end_offset - $section_start_offset);
-        $content_lines = \explode("\r\n", trim($content_lines_str . "\r\n"));
-        $boundary_value = \substr($this->buffer, $content_lines_end_offset + 4, $section_end_offset - $content_lines_end_offset - 4);
-        $upload_key = false;
-        foreach ($content_lines as $content_line) {
-            if (!\strpos($content_line, ': ')) {
+        $contentLinesStr = \substr($this->buffer, $sectionStartOffset, $contentLinesEndOffset - $sectionStartOffset);
+        $contentLines = \explode("\r\n", trim($contentLinesStr . "\r\n"));
+        $boundaryValue = \substr($this->buffer, $contentLinesEndOffset + 4, $sectionEndOffset - $contentLinesEndOffset - 4);
+        $uploadKey = false;
+        foreach ($contentLines as $contentLine) {
+            if (!\strpos($contentLine, ': ')) {
                 return 0;
             }
-            list($key, $value) = \explode(': ', $content_line);
+            list($key, $value) = \explode(': ', $contentLine);
             switch (strtolower($key)) {
                 case "content-disposition":
                     // Is file data.
                     if (\preg_match('/name="(.*?)"; filename="(.*?)"/i', $value, $match)) {
                         $error = 0;
-                        $tmp_file = '';
-                        $size = \strlen($boundary_value);
-                        $tmp_upload_dir = HTTP::uploadTmpDir();
-                        if (!$tmp_upload_dir) {
+                        $tmpFile = '';
+                        $size = \strlen($boundaryValue);
+                        $tmpUploadDir = HTTP::uploadTmpDir();
+                        if (!$tmpUploadDir) {
                             $error = UPLOAD_ERR_NO_TMP_DIR;
-                        } else if ($boundary_value === '') {
+                        } else if ($boundaryValue === '') {
                             $error = UPLOAD_ERR_NO_FILE;
                         } else {
-                            $tmp_file = \tempnam($tmp_upload_dir, 'workerman.upload.');
-                            if ($tmp_file === false || false == \file_put_contents($tmp_file, $boundary_value)) {
+                            $tmpFile = \tempnam($tmpUploadDir, 'workerman.upload.');
+                            if ($tmpFile === false || false == \file_put_contents($tmpFile, $boundaryValue)) {
                                 $error = UPLOAD_ERR_CANT_WRITE;
                             }
                         }
-                        $upload_key = $match[1];
+                        $uploadKey = $match[1];
                         // Parse upload files.
                         $file = [
                             'name' => $match[2],
-                            'tmp_name' => $tmp_file,
+                            'tmp_name' => $tmpFile,
                             'size' => $size,
                             'error' => $error,
                             'type' => '',
@@ -588,9 +588,9 @@ class Request
                         // Parse $POST.
                         if (\preg_match('/name="(.*?)"$/', $value, $match)) {
                             $k = $match[1];
-                            $post_encode_string .= \urlencode($k) . "=" . \urlencode($boundary_value) . '&';
+                            $postEncodeString .= \urlencode($k) . "=" . \urlencode($boundaryValue) . '&';
                         }
-                        return $section_end_offset + \strlen($boundary) + 2;
+                        return $sectionEndOffset + \strlen($boundary) + 2;
                     }
                     break;
                 case "content-type":
@@ -598,13 +598,13 @@ class Request
                     break;
             }
         }
-        if ($upload_key === false) {
+        if ($uploadKey === false) {
             return 0;
         }
-        $files_encode_str .= \urlencode($upload_key) . '=' . \count($files) . '&';
+        $filesEncodeStr .= \urlencode($uploadKey) . '=' . \count($files) . '&';
         $files[] = $file;
 
-        return $section_end_offset + \strlen($boundary) + 2;
+        return $sectionEndOffset + \strlen($boundary) + 2;
     }
 
     /**
@@ -690,19 +690,19 @@ class Request
     }
 
     /**
-     * @param string $session_name
+     * @param string $sessionName
      * @param string $sid
-     * @param array $cookie_params
+     * @param array $cookieParams
      * @return void
      */
-    protected function setSidCookie(string $session_name, string $sid, array $cookie_params)
+    protected function setSidCookie(string $sessionName, string $sid, array $cookieParams)
     {
-        $this->connection->header['Set-Cookie'] = [$session_name . '=' . $sid
-            . (empty($cookie_params['domain']) ? '' : '; Domain=' . $cookie_params['domain'])
-            . (empty($cookie_params['lifetime']) ? '' : '; Max-Age=' . $cookie_params['lifetime'])
-            . (empty($cookie_params['path']) ? '' : '; Path=' . $cookie_params['path'])
-            . (empty($cookie_params['samesite']) ? '' : '; SameSite=' . $cookie_params['samesite'])
-            . (!$cookie_params['secure'] ? '' : '; Secure')
-            . (!$cookie_params['httponly'] ? '' : '; HttpOnly')];
+        $this->connection->header['Set-Cookie'] = [$sessionName . '=' . $sid
+            . (empty($cookieParams['domain']) ? '' : '; Domain=' . $cookieParams['domain'])
+            . (empty($cookieParams['lifetime']) ? '' : '; Max-Age=' . $cookieParams['lifetime'])
+            . (empty($cookieParams['path']) ? '' : '; Path=' . $cookieParams['path'])
+            . (empty($cookieParams['samesite']) ? '' : '; SameSite=' . $cookieParams['samesite'])
+            . (!$cookieParams['secure'] ? '' : '; Secure')
+            . (!$cookieParams['httponly'] ? '' : '; HttpOnly')];
     }
 }

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

@@ -248,13 +248,13 @@ class Response
      * Set status.
      *
      * @param int $code
-     * @param string|null $reason_phrase
+     * @param string|null $reasonPhrase
      * @return $this
      */
-    public function withStatus($code, $reason_phrase = null)
+    public function withStatus($code, $reasonPhrase = null)
     {
         $this->status = $code;
-        $this->reason = $reason_phrase;
+        $this->reason = $reasonPhrase;
         return $this;
     }
 
@@ -334,35 +334,35 @@ class Response
      *
      * @param $name
      * @param string $value
-     * @param int $max_age
+     * @param int $maxAge
      * @param string $path
      * @param string $domain
      * @param bool $secure
-     * @param bool $http_only
-     * @param bool $same_site
+     * @param bool $httpOnly
+     * @param bool $sameSite
      * @return $this
      */
-    public function cookie($name, $value = '', $max_age = null, $path = '', $domain = '', $secure = false, $http_only = false, $same_site  = false)
+    public function cookie($name, $value = '', $maxAge = null, $path = '', $domain = '', $secure = false, $httpOnly = false, $sameSite  = false)
     {
         $this->header['Set-Cookie'][] = $name . '=' . \rawurlencode($value)
             . (empty($domain) ? '' : '; Domain=' . $domain)
-            . ($max_age === null ? '' : '; Max-Age=' . $max_age)
+            . ($maxAge === null ? '' : '; Max-Age=' . $maxAge)
             . (empty($path) ? '' : '; Path=' . $path)
             . (!$secure ? '' : '; Secure')
-            . (!$http_only ? '' : '; HttpOnly')
-            . (empty($same_site) ? '' : '; SameSite=' . $same_site);
+            . (!$httpOnly ? '' : '; HttpOnly')
+            . (empty($sameSite) ? '' : '; SameSite=' . $sameSite);
         return $this;
     }
 
     /**
      * Create header for file.
      *
-     * @param array $file_info
+     * @param array $fileInfo
      * @return string
      */
-    protected function createHeadForFile($file_info)
+    protected function createHeadForFile($fileInfo)
     {
-        $file = $file_info['file'];
+        $file = $fileInfo['file'];
         $reason = $this->reason ?: self::PHRASES[$this->status];
         $head = "HTTP/{$this->version} {$this->status} $reason\r\n";
         $headers = $this->header;
@@ -383,9 +383,9 @@ class Response
             $head .= "Connection: keep-alive\r\n";
         }
 
-        $file_info = \pathinfo($file);
-        $extension = $file_info['extension'] ?? '';
-        $base_name = $file_info['basename'] ?? 'unknown';
+        $fileInfo = \pathinfo($file);
+        $extension = $fileInfo['extension'] ?? '';
+        $baseName = $fileInfo['basename'] ?? 'unknown';
         if (!isset($headers['Content-Type'])) {
             if (isset(self::$mimeTypeMap[$extension])) {
                 $head .= "Content-Type: " . self::$mimeTypeMap[$extension] . "\r\n";
@@ -395,7 +395,7 @@ class Response
         }
 
         if (!isset($headers['Content-Disposition']) && !isset(self::$mimeTypeMap[$extension])) {
-            $head .= "Content-Disposition: attachment; filename=\"$base_name\"\r\n";
+            $head .= "Content-Disposition: attachment; filename=\"$baseName\"\r\n";
         }
 
         if (!isset($headers['Last-Modified'])) {
@@ -419,9 +419,9 @@ class Response
         }
 
         $reason = $this->reason ?: self::PHRASES[$this->status] ?? '';
-        $body_len = \strlen($this->body);
+        $bodyLen = \strlen($this->body);
         if (empty($this->header)) {
-            return "HTTP/{$this->version} {$this->status} $reason\r\nServer: workerman\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $body_len\r\nConnection: keep-alive\r\n\r\n{$this->body}";
+            return "HTTP/{$this->version} {$this->status} $reason\r\nServer: workerman\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $bodyLen\r\nConnection: keep-alive\r\n\r\n{$this->body}";
         }
 
         $head = "HTTP/{$this->version} {$this->status} $reason\r\n";
@@ -450,9 +450,9 @@ class Response
         }
 
         if (!isset($headers['Transfer-Encoding'])) {
-            $head .= "Content-Length: $body_len\r\n\r\n";
+            $head .= "Content-Length: $bodyLen\r\n\r\n";
         } else {
-            return "$head\r\n" . dechex($body_len) . "\r\n{$this->body}\r\n";
+            return "$head\r\n" . dechex($bodyLen) . "\r\n{$this->body}\r\n";
         }
 
         // The whole http package
@@ -466,15 +466,15 @@ class Response
      */
     public static function initMimeTypeMap()
     {
-        $mime_file = __DIR__ . '/mime.types';
-        $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
+        $mimeFile = __DIR__ . '/mime.types';
+        $items = \file($mimeFile, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
         foreach ($items as $content) {
             if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
-                $mime_type = $match[1];
-                $extension_var = $match[2];
-                $extension_array = \explode(' ', \substr($extension_var, 0, -1));
-                foreach ($extension_array as $file_extension) {
-                    static::$mimeTypeMap[$file_extension] = $mime_type;
+                $mimeType = $match[1];
+                $extensionVar = $match[2];
+                $extensionArray = \explode(' ', \substr($extensionVar, 0, -1));
+                foreach ($extensionArray as $fileExtension) {
+                    static::$mimeTypeMap[$fileExtension] = $mimeType;
                 }
             }
         }

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

@@ -138,16 +138,16 @@ class Session
     /**
      * Session constructor.
      *
-     * @param string $session_id
+     * @param string $sessionId
      */
-    public function __construct($session_id)
+    public function __construct($sessionId)
     {
-        static::checkSessionId($session_id);
+        static::checkSessionId($sessionId);
         if (static::$handler === null) {
             static::initHandler();
         }
-        $this->sessionId = $session_id;
-        if ($data = static::$handler->read($session_id)) {
+        $this->sessionId = $sessionId;
+        if ($data = static::$handler->read($sessionId)) {
             $this->data = \unserialize($data);
         }
     }
@@ -328,33 +328,33 @@ class Session
      */
     public static function init()
     {
-        if (($gc_probability = (int)\ini_get('session.gc_probability')) && ($gc_divisor = (int)\ini_get('session.gc_divisor'))) {
-            static::$gcProbability = [$gc_probability, $gc_divisor];
+        if (($gcProbability = (int)\ini_get('session.gc_probability')) && ($gcDivisor = (int)\ini_get('session.gc_divisor'))) {
+            static::$gcProbability = [$gcProbability, $gcDivisor];
         }
 
-        if ($gc_max_life_time = \ini_get('session.gc_maxlifetime')) {
-            self::$lifetime = (int)$gc_max_life_time;
+        if ($gcMaxLifeTime = \ini_get('session.gc_maxlifetime')) {
+            self::$lifetime = (int)$gcMaxLifeTime;
         }
 
-        $session_cookie_params = \session_get_cookie_params();
-        static::$cookieLifetime = $session_cookie_params['lifetime'];
-        static::$cookiePath = $session_cookie_params['path'];
-        static::$domain = $session_cookie_params['domain'];
-        static::$secure = $session_cookie_params['secure'];
-        static::$httpOnly = $session_cookie_params['httponly'];
+        $sessionCookieParams = \session_get_cookie_params();
+        static::$cookieLifetime = $sessionCookieParams['lifetime'];
+        static::$cookiePath = $sessionCookieParams['path'];
+        static::$domain = $sessionCookieParams['domain'];
+        static::$secure = $sessionCookieParams['secure'];
+        static::$httpOnly = $sessionCookieParams['httponly'];
     }
 
     /**
      * Set session handler class.
      *
-     * @param mixed|null $class_name
+     * @param mixed|null $className
      * @param mixed|null $config
      * @return string
      */
-    public static function handlerClass($class_name = null, $config = null)
+    public static function handlerClass($className = null, $config = null)
     {
-        if ($class_name) {
-            static::$handlerClass = $class_name;
+        if ($className) {
+            static::$handlerClass = $className;
         }
         if ($config) {
             static::$handlerConfig = $config;
@@ -419,12 +419,12 @@ class Session
     /**
      * Check session id.
      *
-     * @param string $session_id
+     * @param string $sessionId
      */
-    protected static function checkSessionId($session_id)
+    protected static function checkSessionId($sessionId)
     {
-        if (!\preg_match('/^[a-zA-Z0-9]+$/', $session_id)) {
-            throw new SessionException("session_id $session_id is invalid");
+        if (!\preg_match('/^[a-zA-Z0-9]+$/', $sessionId)) {
+            throw new SessionException("session_id $sessionId is invalid");
         }
     }
 }

+ 28 - 28
src/Protocols/Http/Session/FileSessionHandler.php

@@ -41,11 +41,11 @@ class FileSessionHandler implements SessionHandlerInterface
      */
     public static function init()
     {
-        $save_path = @\session_save_path();
-        if (!$save_path || \strpos($save_path, 'tcp://') === 0) {
-            $save_path = \sys_get_temp_dir();
+        $savePath = @\session_save_path();
+        if (!$savePath || \strpos($savePath, 'tcp://') === 0) {
+            $savePath = \sys_get_temp_dir();
         }
-        static::sessionSavePath($save_path);
+        static::sessionSavePath($savePath);
     }
 
     /**
@@ -62,7 +62,7 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function open($save_path, $name)
+    public function open($savePath, $name)
     {
         return true;
     }
@@ -70,16 +70,16 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function read($session_id)
+    public function read($sessionId)
     {
-        $session_file = static::sessionFile($session_id);
+        $sessionFile = static::sessionFile($sessionId);
         \clearstatcache();
-        if (\is_file($session_file)) {
-            if (\time() - \filemtime($session_file) > Session::$lifetime) {
-                \unlink($session_file);
+        if (\is_file($sessionFile)) {
+            if (\time() - \filemtime($sessionFile) > Session::$lifetime) {
+                \unlink($sessionFile);
                 return '';
             }
-            $data = \file_get_contents($session_file);
+            $data = \file_get_contents($sessionFile);
             return $data ?: '';
         }
         return '';
@@ -88,13 +88,13 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function write($session_id, $session_data)
+    public function write($sessionId, $sessionData)
     {
-        $temp_file = static::$sessionSavePath . uniqid(bin2hex(random_bytes(8)), true);
-        if (!\file_put_contents($temp_file, $session_data)) {
+        $tempFile = static::$sessionSavePath . uniqid(bin2hex(random_bytes(8)), true);
+        if (!\file_put_contents($tempFile, $sessionData)) {
             return false;
         }
-        return \rename($temp_file, static::sessionFile($session_id));
+        return \rename($tempFile, static::sessionFile($sessionId));
     }
 
     /**
@@ -110,15 +110,15 @@ class FileSessionHandler implements SessionHandlerInterface
      */
     public function updateTimestamp($id, $data = "")
     {
-        $session_file = static::sessionFile($id);
-        if (!file_exists($session_file)) {
+        $sessionFile = static::sessionFile($id);
+        if (!file_exists($sessionFile)) {
             return false;
         }
         // set file modify time to current time
-        $set_modify_time = \touch($session_file);
+        $setModifyTime = \touch($sessionFile);
         // clear file stat cache
         \clearstatcache();
-        return $set_modify_time;
+        return $setModifyTime;
     }
 
     /**
@@ -132,11 +132,11 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function destroy($session_id)
+    public function destroy($sessionId)
     {
-        $session_file = static::sessionFile($session_id);
-        if (\is_file($session_file)) {
-            \unlink($session_file);
+        $sessionFile = static::sessionFile($sessionId);
+        if (\is_file($sessionFile)) {
+            \unlink($sessionFile);
         }
         return true;
     }
@@ -146,9 +146,9 @@ class FileSessionHandler implements SessionHandlerInterface
      */
     public function gc($maxlifetime)
     {
-        $time_now = \time();
+        $timeNow = \time();
         foreach (\glob(static::$sessionSavePath . static::$sessionFilePrefix . '*') as $file) {
-            if (\is_file($file) && $time_now - \filemtime($file) > $maxlifetime) {
+            if (\is_file($file) && $timeNow - \filemtime($file) > $maxlifetime) {
                 \unlink($file);
             }
         }
@@ -157,12 +157,12 @@ class FileSessionHandler implements SessionHandlerInterface
     /**
      * Get session file path.
      *
-     * @param string $session_id
+     * @param string $sessionId
      * @return string
      */
-    protected static function sessionFile($session_id)
+    protected static function sessionFile($sessionId)
     {
-        return static::$sessionSavePath . static::$sessionFilePrefix . $session_id;
+        return static::$sessionSavePath . static::$sessionFilePrefix . $sessionId;
     }
 
     /**

+ 4 - 4
src/Protocols/Http/Session/RedisClusterSessionHandler.php

@@ -21,10 +21,10 @@ class RedisClusterSessionHandler extends RedisSessionHandler
     public function __construct($config)
     {
         $timeout = $config['timeout'] ?? 2;
-        $read_timeout = $config['read_timeout'] ?? $timeout;
+        $readTimeout = $config['read_timeout'] ?? $timeout;
         $persistent = $config['persistent'] ?? false;
         $auth = $config['auth'] ?? '';
-        $args = [null, $config['host'], $timeout, $read_timeout, $persistent];
+        $args = [null, $config['host'], $timeout, $readTimeout, $persistent];
         if ($auth) {
             $args[] = $auth;
         }
@@ -38,9 +38,9 @@ class RedisClusterSessionHandler extends RedisSessionHandler
     /**
      * {@inheritdoc}
      */
-    public function read($session_id)
+    public function read($sessionId)
     {
-        return $this->redis->get($session_id);
+        return $this->redis->get($sessionId);
     }
 
 }

+ 8 - 8
src/Protocols/Http/Session/RedisSessionHandler.php

@@ -89,7 +89,7 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function open($save_path, $name)
+    public function open($savePath, $name)
     {
         return true;
     }
@@ -97,15 +97,15 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function read($session_id)
+    public function read($sessionId)
     {
         try {
-            return $this->redis->get($session_id);
+            return $this->redis->get($sessionId);
         } catch (RedisException $e) {
             $msg = strtolower($e->getMessage());
             if ($msg === 'connection lost' || strpos($msg, 'went away')) {
                 $this->connect();
-                return $this->redis->get($session_id);
+                return $this->redis->get($sessionId);
             }
             throw $e;
         }
@@ -114,9 +114,9 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function write($session_id, $session_data)
+    public function write($sessionId, $sessionData)
     {
-        return true === $this->redis->setex($session_id, Session::$lifetime, $session_data);
+        return true === $this->redis->setex($sessionId, Session::$lifetime, $sessionData);
     }
 
     /**
@@ -130,9 +130,9 @@ class RedisSessionHandler implements SessionHandlerInterface
     /**
      * {@inheritdoc}
      */
-    public function destroy($session_id)
+    public function destroy($sessionId)
     {
-        $this->redis->del($session_id);
+        $this->redis->del($sessionId);
         return true;
     }
 

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

@@ -30,14 +30,14 @@ interface SessionHandlerInterface
     /**
      * Destroy a session
      * @link http://php.net/manual/en/sessionhandlerinterface.destroy.php
-     * @param string $session_id The session ID being destroyed.
+     * @param string $sessionId The session ID being destroyed.
      * @return bool <p>
      * The return value (usually TRUE on success, FALSE on failure).
      * Note this value is returned internally to PHP for processing.
      * </p>
      * @since 5.4.0
      */
-    public function destroy($session_id);
+    public function destroy($sessionId);
 
     /**
      * Cleanup old sessions
@@ -57,7 +57,7 @@ interface SessionHandlerInterface
     /**
      * Initialize session
      * @link http://php.net/manual/en/sessionhandlerinterface.open.php
-     * @param string $save_path The path where to store/retrieve the session.
+     * @param string $savePath The path where to store/retrieve the session.
      * @param string $name The session name.
      * @return bool <p>
      * The return value (usually TRUE on success, FALSE on failure).
@@ -65,13 +65,13 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function open($save_path, $name);
+    public function open($savePath, $name);
 
 
     /**
      * Read session data
      * @link http://php.net/manual/en/sessionhandlerinterface.read.php
-     * @param string $session_id The session id to read data for.
+     * @param string $sessionId The session id to read data for.
      * @return string <p>
      * Returns an encoded string of the read data.
      * If nothing was read, it must return an empty string.
@@ -79,13 +79,13 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function read($session_id);
+    public function read($sessionId);
 
     /**
      * Write session data
      * @link http://php.net/manual/en/sessionhandlerinterface.write.php
-     * @param string $session_id The session id.
-     * @param string $session_data <p>
+     * @param string $sessionId The session id.
+     * @param string $sessionData <p>
      * The encoded session data. This data is the
      * result of the PHP internally encoding
      * the $SESSION superglobal to a serialized
@@ -98,7 +98,7 @@ interface SessionHandlerInterface
      * </p>
      * @since 5.4.0
      */
-    public function write($session_id, $session_data);
+    public function write($sessionId, $sessionData);
 
     /**
      * Update sesstion modify time.

+ 4 - 4
src/Protocols/ProtocolInterface.php

@@ -27,20 +27,20 @@ interface ProtocolInterface
      * If length is unknow please return 0 that mean wating more data.
      * If the package has something wrong please return false the connection will be closed.
      *
-     * @param string $recv_buffer
+     * @param string $recvBuffer
      * @param ConnectionInterface $connection
      * @return int|false
      */
-    public static function input($recv_buffer, ConnectionInterface $connection);
+    public static function input($recvBuffer, ConnectionInterface $connection);
 
     /**
      * Decode package and emit onMessage($message) callback, $message is the result that decode returned.
      *
-     * @param string $recv_buffer
+     * @param string $recvBuffer
      * @param ConnectionInterface $connection
      * @return mixed
      */
-    public static function decode($recv_buffer, ConnectionInterface $connection);
+    public static function decode($recvBuffer, ConnectionInterface $connection);
 
     /**
      * Encode package brefore sending to client.

+ 81 - 81
src/Protocols/Websocket.php

@@ -48,9 +48,9 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
     public static function input($buffer, ConnectionInterface $connection)
     {
         // Receive length.
-        $recv_len = \strlen($buffer);
+        $recvLen = \strlen($buffer);
         // We need more data.
-        if ($recv_len < 6) {
+        if ($recvLen < 6) {
             return 0;
         }
 
@@ -62,15 +62,15 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
         // Buffer websocket frame data.
         if ($connection->context->websocketCurrentFrameLength) {
             // We need more frame data.
-            if ($connection->context->websocketCurrentFrameLength > $recv_len) {
+            if ($connection->context->websocketCurrentFrameLength > $recvLen) {
                 // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
                 return 0;
             }
         } else {
             $firstbyte = \ord($buffer[0]);
             $secondbyte = \ord($buffer[1]);
-            $data_len = $secondbyte & 127;
-            $is_fin_frame = $firstbyte >> 7;
+            $dataLen = $secondbyte & 127;
+            $isFinFrame = $firstbyte >> 7;
             $masked = $secondbyte >> 7;
 
             if (!$masked) {
@@ -92,10 +92,10 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 // Close package.
                 case 0x8:
                     // Try to emit onWebSocketClose callback.
-                    $close_cb = $connection->onWebSocketClose ?? $connection->worker->onWebSocketClose ?? false;
-                    if ($close_cb) {
+                    $closeCb = $connection->onWebSocketClose ?? $connection->worker->onWebSocketClose ?? false;
+                    if ($closeCb) {
                         try {
-                            $close_cb($connection);
+                            $closeCb($connection);
                         } catch (\Throwable $e) {
                             Worker::stopAll(250, $e);
                         }
@@ -118,98 +118,98 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             }
 
             // Calculate packet length.
-            $head_len = 6;
-            if ($data_len === 126) {
-                $head_len = 8;
-                if ($head_len > $recv_len) {
+            $headLen = 6;
+            if ($dataLen === 126) {
+                $headLen = 8;
+                if ($headLen > $recvLen) {
                     return 0;
                 }
                 $pack = \unpack('nn/ntotal_len', $buffer);
-                $data_len = $pack['total_len'];
+                $dataLen = $pack['total_len'];
             } else {
-                if ($data_len === 127) {
-                    $head_len = 14;
-                    if ($head_len > $recv_len) {
+                if ($dataLen === 127) {
+                    $headLen = 14;
+                    if ($headLen > $recvLen) {
                         return 0;
                     }
                     $arr = \unpack('n/N2c', $buffer);
-                    $data_len = $arr['c1'] * 4294967296 + $arr['c2'];
+                    $dataLen = $arr['c1'] * 4294967296 + $arr['c2'];
                 }
             }
-            $current_frame_length = $head_len + $data_len;
+            $currentFrameLength = $headLen + $dataLen;
 
-            $total_package_size = \strlen($connection->context->websocketDataBuffer) + $current_frame_length;
-            if ($total_package_size > $connection->maxPackageSize) {
-                Worker::safeEcho("error package. package_length=$total_package_size\n");
+            $totalPackageSize = \strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
+            if ($totalPackageSize > $connection->maxPackageSize) {
+                Worker::safeEcho("error package. package_length=$totalPackageSize\n");
                 $connection->close();
                 return 0;
             }
 
-            if ($is_fin_frame) {
+            if ($isFinFrame) {
                 if ($opcode === 0x9) {
-                    if ($recv_len >= $current_frame_length) {
-                        $ping_data = static::decode(\substr($buffer, 0, $current_frame_length), $connection);
-                        $connection->consumeRecvBuffer($current_frame_length);
-                        $tmp_connection_type = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
+                    if ($recvLen >= $currentFrameLength) {
+                        $pingData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $connection->consumeRecvBuffer($currentFrameLength);
+                        $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
-                        $ping_cb = $connection->onWebSocketPing ?? $connection->worker->onWebSocketPing ?? false;
-                        if ($ping_cb) {
+                        $pingCb = $connection->onWebSocketPing ?? $connection->worker->onWebSocketPing ?? false;
+                        if ($pingCb) {
                             try {
-                                $ping_cb($connection, $ping_data);
+                                $pingCb($connection, $pingData);
                             } catch (\Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         } else {
-                            $connection->send($ping_data);
+                            $connection->send($pingData);
                         }
-                        $connection->websocketType = $tmp_connection_type;
-                        if ($recv_len > $current_frame_length) {
-                            return static::input(\substr($buffer, $current_frame_length), $connection);
+                        $connection->websocketType = $tmpConnectionType;
+                        if ($recvLen > $currentFrameLength) {
+                            return static::input(\substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
                 } else if ($opcode === 0xa) {
-                    if ($recv_len >= $current_frame_length) {
-                        $pong_data = static::decode(\substr($buffer, 0, $current_frame_length), $connection);
-                        $connection->consumeRecvBuffer($current_frame_length);
-                        $tmp_connection_type = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
+                    if ($recvLen >= $currentFrameLength) {
+                        $pongData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $connection->consumeRecvBuffer($currentFrameLength);
+                        $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
                         // Try to emit onWebSocketPong callback.
-                        $pong_cb = $connection->onWebSocketPong ?? $connection->worker->onWebSocketPong ?? false;
-                        if ($pong_cb) {
+                        $pongCb = $connection->onWebSocketPong ?? $connection->worker->onWebSocketPong ?? false;
+                        if ($pongCb) {
                             try {
-                                $pong_cb($connection, $pong_data);
+                                $pongCb($connection, $pongData);
                             } catch (\Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         }
-                        $connection->websocketType = $tmp_connection_type;
-                        if ($recv_len > $current_frame_length) {
-                            return static::input(\substr($buffer, $current_frame_length), $connection);
+                        $connection->websocketType = $tmpConnectionType;
+                        if ($recvLen > $currentFrameLength) {
+                            return static::input(\substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
                 }
-                return $current_frame_length;
+                return $currentFrameLength;
             } else {
-                $connection->context->websocketCurrentFrameLength = $current_frame_length;
+                $connection->context->websocketCurrentFrameLength = $currentFrameLength;
             }
         }
 
         // Received just a frame length data.
-        if ($connection->context->websocketCurrentFrameLength === $recv_len) {
+        if ($connection->context->websocketCurrentFrameLength === $recvLen) {
             static::decode($buffer, $connection);
             $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
             $connection->context->websocketCurrentFrameLength = 0;
             return 0;
         } // The length of the received data is greater than the length of a frame.
-        elseif ($connection->context->websocketCurrentFrameLength < $recv_len) {
+        elseif ($connection->context->websocketCurrentFrameLength < $recvLen) {
             static::decode(\substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
             $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
-            $current_frame_length = $connection->context->websocketCurrentFrameLength;
+            $currentFrameLength = $connection->context->websocketCurrentFrameLength;
             $connection->context->websocketCurrentFrameLength = 0;
             // Continue to read next frame.
-            return static::input(\substr($buffer, $current_frame_length), $connection);
+            return static::input(\substr($buffer, $currentFrameLength), $connection);
         } // The length of the received data is less than the length of a frame.
         else {
             return 0;
@@ -233,15 +233,15 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             $connection->websocketType = static::BINARY_TYPE_BLOB;
         }
 
-        $first_byte = $connection->websocketType;
+        $firstByte = $connection->websocketType;
 
         if ($len <= 125) {
-            $encode_buffer = $first_byte . \chr($len) . $buffer;
+            $encodeBuffer = $firstByte . \chr($len) . $buffer;
         } else {
             if ($len <= 65535) {
-                $encode_buffer = $first_byte . \chr(126) . \pack("n", $len) . $buffer;
+                $encodeBuffer = $firstByte . \chr(126) . \pack("n", $len) . $buffer;
             } else {
-                $encode_buffer = $first_byte . \chr(127) . \pack("xxxxN", $len) . $buffer;
+                $encodeBuffer = $firstByte . \chr(127) . \pack("xxxxN", $len) . $buffer;
             }
         }
 
@@ -261,7 +261,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 }
                 return '';
             }
-            $connection->context->tmpWebsocketData .= $encode_buffer;
+            $connection->context->tmpWebsocketData .= $encodeBuffer;
             // Check buffer is full.
             if ($connection->maxSendBufferSize <= \strlen($connection->context->tmpWebsocketData)) {
                 if ($connection->onBufferFull) {
@@ -276,7 +276,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             return '';
         }
 
-        return $encode_buffer;
+        return $encodeBuffer;
     }
 
     /**
@@ -288,9 +288,9 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
      */
     public static function decode($buffer, ConnectionInterface $connection)
     {
-        $first_byte = \ord($buffer[1]);
-        $len = $first_byte & 127;
-        $rsv1 = $first_byte & 64;
+        $firstByte = \ord($buffer[1]);
+        $len = $firstByte & 127;
+        $rsv1 = $firstByte & 64;
 
         if ($len === 126) {
             $masks = \substr($buffer, 4, 4);
@@ -331,29 +331,29 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
         // HTTP protocol.
         if (0 === \strpos($buffer, 'GET')) {
             // Find \r\n\r\n.
-            $header_end_pos = \strpos($buffer, "\r\n\r\n");
-            if (!$header_end_pos) {
+            $headerEndPos = \strpos($buffer, "\r\n\r\n");
+            if (!$headerEndPos) {
                 return 0;
             }
-            $header_length = $header_end_pos + 4;
+            $headerLength = $headerEndPos + 4;
 
             // Get Sec-WebSocket-Key.
-            $Sec_WebSocket_Key = '';
+            $SecWebSocketKey = '';
             if (\preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
-                $Sec_WebSocket_Key = $match[1];
+                $SecWebSocketKey = $match[1];
             } else {
                 $connection->close("HTTP/1.1 200 WebSocket\r\nServer: workerman/" . Worker::VERSION . "\r\n\r\n<div style=\"text-align:center\"><h1>WebSocket</h1><hr>workerman/" . Worker::VERSION . "</div>",
                     true);
                 return 0;
             }
             // Calculation websocket key.
-            $new_key = \base64_encode(\sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
+            $newKey = \base64_encode(\sha1($SecWebSocketKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
             // Handshake response data.
-            $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n"
+            $handshakeMessage = "HTTP/1.1 101 Switching Protocols\r\n"
                 . "Upgrade: websocket\r\n"
                 . "Sec-WebSocket-Version: 13\r\n"
                 . "Connection: Upgrade\r\n"
-                . "Sec-WebSocket-Accept: " . $new_key . "\r\n";
+                . "Sec-WebSocket-Accept: " . $newKey . "\r\n";
 
             // Websocket data buffer.
             $connection->context->websocketDataBuffer = '';
@@ -362,13 +362,13 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             // Current websocket frame data.
             $connection->context->websocketCurrentFrameBuffer = '';
             // Consume handshake data.
-            $connection->consumeRecvBuffer($header_length);
+            $connection->consumeRecvBuffer($headerLength);
 
             // Try to emit onWebSocketConnect callback.
-            $on_websocket_connect = $connection->onWebSocketConnect ?? $connection->worker->onWebSocketConnect ?? false;
-            if ($on_websocket_connect) {
+            $onWebsocketConnect = $connection->onWebSocketConnect ?? $connection->worker->onWebSocketConnect ?? false;
+            if ($onWebsocketConnect) {
                 try {
-                    $on_websocket_connect($connection, new Request($buffer));
+                    $onWebsocketConnect($connection, new Request($buffer));
                 } catch (\Throwable $e) {
                     Worker::stopAll(250, $e);
                 }
@@ -379,29 +379,29 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 $connection->websocketType = static::BINARY_TYPE_BLOB;
             }
 
-            $has_server_header = false;
+            $hasServerHeader = false;
 
             if (isset($connection->headers)) {
                 if (\is_array($connection->headers)) {
                     foreach ($connection->headers as $header) {
                         if (\stripos($header, 'Server:') === 0) {
-                            $has_server_header = true;
+                            $hasServerHeader = true;
                         }
-                        $handshake_message .= "$header\r\n";
+                        $handshakeMessage .= "$header\r\n";
                     }
                 } else {
                     if (\stripos($connection->headers, 'Server:') !== false) {
-                        $has_server_header = true;
+                        $hasServerHeader = true;
                     }
-                    $handshake_message .= "$connection->headers\r\n";
+                    $handshakeMessage .= "$connection->headers\r\n";
                 }
             }
-            if (!$has_server_header) {
-                $handshake_message .= "Server: workerman/" . Worker::VERSION . "\r\n";
+            if (!$hasServerHeader) {
+                $handshakeMessage .= "Server: workerman/" . Worker::VERSION . "\r\n";
             }
-            $handshake_message .= "\r\n";
+            $handshakeMessage .= "\r\n";
             // Send handshake response.
-            $connection->send($handshake_message, true);
+            $connection->send($handshakeMessage, true);
             // Mark handshake complete..
             $connection->context->websocketHandshake = true;
 
@@ -410,8 +410,8 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 $connection->send($connection->context->tmpWebsocketData, true);
                 $connection->context->tmpWebsocketData = '';
             }
-            if (\strlen($buffer) > $header_length) {
-                return static::input(\substr($buffer, $header_length), $connection);
+            if (\strlen($buffer) > $headerLength) {
+                return static::input(\substr($buffer, $headerLength), $connection);
             }
             return 0;
         }

+ 69 - 69
src/Protocols/Ws.php

@@ -55,14 +55,14 @@ class Ws
         if ($connection->handshakeStep === 1) {
             return self::dealHandshake($buffer, $connection);
         }
-        $recv_len = \strlen($buffer);
-        if ($recv_len < 2) {
+        $recvLen = \strlen($buffer);
+        if ($recvLen < 2) {
             return 0;
         }
         // Buffer websocket frame data.
         if ($connection->websocketCurrentFrameLength) {
             // We need more frame data.
-            if ($connection->websocketCurrentFrameLength > $recv_len) {
+            if ($connection->websocketCurrentFrameLength > $recvLen) {
                 // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
                 return 0;
             }
@@ -70,8 +70,8 @@ class Ws
 
             $firstbyte = \ord($buffer[0]);
             $secondbyte = \ord($buffer[1]);
-            $data_len = $secondbyte & 127;
-            $is_fin_frame = $firstbyte >> 7;
+            $dataLen = $secondbyte & 127;
+            $isFinFrame = $firstbyte >> 7;
             $masked = $secondbyte >> 7;
 
             if ($masked) {
@@ -118,92 +118,92 @@ class Ws
                     return 0;
             }
             // Calculate packet length.
-            if ($data_len === 126) {
+            if ($dataLen === 126) {
                 if (\strlen($buffer) < 4) {
                     return 0;
                 }
                 $pack = \unpack('nn/ntotal_len', $buffer);
-                $current_frame_length = $pack['total_len'] + 4;
-            } else if ($data_len === 127) {
+                $currentFrameLength = $pack['total_len'] + 4;
+            } else if ($dataLen === 127) {
                 if (\strlen($buffer) < 10) {
                     return 0;
                 }
                 $arr = \unpack('n/N2c', $buffer);
-                $current_frame_length = $arr['c1'] * 4294967296 + $arr['c2'] + 10;
+                $currentFrameLength = $arr['c1'] * 4294967296 + $arr['c2'] + 10;
             } else {
-                $current_frame_length = $data_len + 2;
+                $currentFrameLength = $dataLen + 2;
             }
 
-            $total_package_size = \strlen($connection->websocketDataBuffer) + $current_frame_length;
-            if ($total_package_size > $connection->maxPackageSize) {
-                Worker::safeEcho("error package. package_length=$total_package_size\n");
+            $totalPackageSize = \strlen($connection->websocketDataBuffer) + $currentFrameLength;
+            if ($totalPackageSize > $connection->maxPackageSize) {
+                Worker::safeEcho("error package. package_length=$totalPackageSize\n");
                 $connection->close();
                 return 0;
             }
 
-            if ($is_fin_frame) {
+            if ($isFinFrame) {
                 if ($opcode === 0x9) {
-                    if ($recv_len >= $current_frame_length) {
-                        $ping_data = static::decode(\substr($buffer, 0, $current_frame_length), $connection);
-                        $connection->consumeRecvBuffer($current_frame_length);
-                        $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
+                    if ($recvLen >= $currentFrameLength) {
+                        $pingData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $connection->consumeRecvBuffer($currentFrameLength);
+                        $tmpConnectionType = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
                         if (isset($connection->onWebSocketPing)) {
                             try {
-                                ($connection->onWebSocketPing)($connection, $ping_data);
+                                ($connection->onWebSocketPing)($connection, $pingData);
                             } catch (\Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         } else {
-                            $connection->send($ping_data);
+                            $connection->send($pingData);
                         }
-                        $connection->websocketType = $tmp_connection_type;
-                        if ($recv_len > $current_frame_length) {
-                            return static::input(\substr($buffer, $current_frame_length), $connection);
+                        $connection->websocketType = $tmpConnectionType;
+                        if ($recvLen > $currentFrameLength) {
+                            return static::input(\substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
 
                 } else if ($opcode === 0xa) {
-                    if ($recv_len >= $current_frame_length) {
-                        $pong_data = static::decode(\substr($buffer, 0, $current_frame_length), $connection);
-                        $connection->consumeRecvBuffer($current_frame_length);
-                        $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
+                    if ($recvLen >= $currentFrameLength) {
+                        $pongData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $connection->consumeRecvBuffer($currentFrameLength);
+                        $tmpConnectionType = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
                         // Try to emit onWebSocketPong callback.
                         if (isset($connection->onWebSocketPong)) {
                             try {
-                                ($connection->onWebSocketPong)($connection, $pong_data);
+                                ($connection->onWebSocketPong)($connection, $pongData);
                             } catch (\Throwable $e) {
                                 Worker::stopAll(250, $e);
                             }
                         }
-                        $connection->websocketType = $tmp_connection_type;
-                        if ($recv_len > $current_frame_length) {
-                            return static::input(\substr($buffer, $current_frame_length), $connection);
+                        $connection->websocketType = $tmpConnectionType;
+                        if ($recvLen > $currentFrameLength) {
+                            return static::input(\substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
                 }
-                return $current_frame_length;
+                return $currentFrameLength;
             } else {
-                $connection->websocketCurrentFrameLength = $current_frame_length;
+                $connection->websocketCurrentFrameLength = $currentFrameLength;
             }
         }
         // Received just a frame length data.
-        if ($connection->websocketCurrentFrameLength === $recv_len) {
+        if ($connection->websocketCurrentFrameLength === $recvLen) {
             self::decode($buffer, $connection);
             $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
             $connection->websocketCurrentFrameLength = 0;
             return 0;
         } // The length of the received data is greater than the length of a frame.
-        elseif ($connection->websocketCurrentFrameLength < $recv_len) {
+        elseif ($connection->websocketCurrentFrameLength < $recvLen) {
             self::decode(\substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
             $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
-            $current_frame_length = $connection->websocketCurrentFrameLength;
+            $currentFrameLength = $connection->websocketCurrentFrameLength;
             $connection->websocketCurrentFrameLength = 0;
             // Continue to read next frame.
-            return self::input(\substr($buffer, $current_frame_length), $connection);
+            return self::input(\substr($buffer, $currentFrameLength), $connection);
         } // The length of the received data is less than the length of a frame.
         else {
             return 0;
@@ -227,25 +227,25 @@ class Ws
             static::sendHandshake($connection);
         }
         $mask = 1;
-        $mask_key = "\x00\x00\x00\x00";
+        $maskKey = "\x00\x00\x00\x00";
 
         $pack = '';
-        $length = $length_flag = \strlen($payload);
+        $length = $lengthFlag = \strlen($payload);
         if (65535 < $length) {
             $pack = \pack('NN', ($length & 0xFFFFFFFF00000000) >> 32, $length & 0x00000000FFFFFFFF);
-            $length_flag = 127;
+            $lengthFlag = 127;
         } else if (125 < $length) {
             $pack = \pack('n*', $length);
-            $length_flag = 126;
+            $lengthFlag = 126;
         }
 
-        $head = ($mask << 7) | $length_flag;
+        $head = ($mask << 7) | $lengthFlag;
         $head = $connection->websocketType . \chr($head) . $pack;
 
-        $frame = $head . $mask_key;
+        $frame = $head . $maskKey;
         // append payload to frame:
-        $mask_key = \str_repeat($mask_key, \floor($length / 4)) . \substr($mask_key, 0, $length % 4);
-        $frame .= $payload ^ $mask_key;
+        $maskKey = \str_repeat($maskKey, \floor($length / 4)) . \substr($maskKey, 0, $length % 4);
+        $frame .= $payload ^ $maskKey;
         if ($connection->handshakeStep === 1) {
             // If buffer has already full then discard the current package.
             if (\strlen($connection->tmpWebsocketData) > $connection->maxSendBufferSize) {
@@ -283,24 +283,24 @@ class Ws
      */
     public static function decode($bytes, ConnectionInterface $connection)
     {
-        $data_length = \ord($bytes[1]);
+        $dataLength = \ord($bytes[1]);
 
-        if ($data_length === 126) {
-            $decoded_data = \substr($bytes, 4);
-        } else if ($data_length === 127) {
-            $decoded_data = \substr($bytes, 10);
+        if ($dataLength === 126) {
+            $decodedData = \substr($bytes, 4);
+        } else if ($dataLength === 127) {
+            $decodedData = \substr($bytes, 10);
         } else {
-            $decoded_data = \substr($bytes, 2);
+            $decodedData = \substr($bytes, 2);
         }
         if ($connection->websocketCurrentFrameLength) {
-            $connection->websocketDataBuffer .= $decoded_data;
+            $connection->websocketDataBuffer .= $decodedData;
             return $connection->websocketDataBuffer;
         } else {
             if ($connection->websocketDataBuffer !== '') {
-                $decoded_data = $connection->websocketDataBuffer . $decoded_data;
+                $decodedData = $connection->websocketDataBuffer . $decodedData;
                 $connection->websocketDataBuffer = '';
             }
-            return $decoded_data;
+            return $decodedData;
         }
     }
 
@@ -347,26 +347,26 @@ class Ws
         $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
         // Handshake header.
         $connection->websocketSecKey = \base64_encode(random_bytes(16));
-        $user_header = $connection->headers ?? $connection->wsHttpHeader ?? null;
-        $user_header_str = '';
-        if (!empty($user_header)) {
-            if (\is_array($user_header)) {
-                foreach ($user_header as $k => $v) {
-                    $user_header_str .= "$k: $v\r\n";
+        $userHeader = $connection->headers ?? $connection->wsHttpHeader ?? null;
+        $userHeaderStr = '';
+        if (!empty($userHeader)) {
+            if (\is_array($userHeader)) {
+                foreach ($userHeader as $k => $v) {
+                    $userHeaderStr .= "$k: $v\r\n";
                 }
             } else {
-                $user_header_str .= $user_header;
+                $userHeaderStr .= $userHeader;
             }
-            $user_header_str = "\r\n" . \trim($user_header_str);
+            $userHeaderStr = "\r\n" . \trim($userHeaderStr);
         }
         $header = 'GET ' . $connection->getRemoteURI() . " HTTP/1.1\r\n" .
-            (!\preg_match("/\nHost:/i", $user_header_str) ? "Host: $host\r\n" : '') .
+            (!\preg_match("/\nHost:/i", $userHeaderStr) ? "Host: $host\r\n" : '') .
             "Connection: Upgrade\r\n" .
             "Upgrade: websocket\r\n" .
             (isset($connection->websocketOrigin) ? "Origin: " . $connection->websocketOrigin . "\r\n" : '') .
             (isset($connection->WSClientProtocol) ? "Sec-WebSocket-Protocol: " . $connection->WSClientProtocol . "\r\n" : '') .
             "Sec-WebSocket-Version: 13\r\n" .
-            "Sec-WebSocket-Key: " . $connection->websocketSecKey . $user_header_str . "\r\n\r\n";
+            "Sec-WebSocket-Key: " . $connection->websocketSecKey . $userHeaderStr . "\r\n\r\n";
         $connection->send($header, true);
         $connection->handshakeStep = 1;
         $connection->websocketCurrentFrameLength = 0;
@@ -406,11 +406,11 @@ class Ws
             }
 
             $connection->handshakeStep = 2;
-            $handshake_response_length = $pos + 4;
+            $handshakeResponseLength = $pos + 4;
             // Try to emit onWebSocketConnect callback.
             if (isset($connection->onWebSocketConnect)) {
                 try {
-                    ($connection->onWebSocketConnect)($connection, \substr($buffer, 0, $handshake_response_length));
+                    ($connection->onWebSocketConnect)($connection, \substr($buffer, 0, $handshakeResponseLength));
                 } catch (\Throwable $e) {
                     Worker::stopAll(250, $e);
                 }
@@ -425,13 +425,13 @@ class Ws
                 });
             }
 
-            $connection->consumeRecvBuffer($handshake_response_length);
+            $connection->consumeRecvBuffer($handshakeResponseLength);
             if (!empty($connection->tmpWebsocketData)) {
                 $connection->send($connection->tmpWebsocketData, true);
                 $connection->tmpWebsocketData = '';
             }
-            if (\strlen($buffer) > $handshake_response_length) {
-                return self::input(\substr($buffer, $handshake_response_length), $connection);
+            if (\strlen($buffer) > $handshakeResponseLength) {
+                return self::input(\substr($buffer, $handshakeResponseLength), $connection);
             }
         }
         return 0;

+ 27 - 27
src/Timer.php

@@ -94,15 +94,15 @@ class Timer
     /**
      * Add a timer.
      *
-     * @param float    $time_interval
+     * @param float    $timeInterval
      * @param callable $func
      * @param mixed    $args
      * @param bool     $persistent
      * @return int|bool
      */
-    public static function add(float $time_interval, $func, $args = [], $persistent = true)
+    public static function add(float $timeInterval, $func, $args = [], $persistent = true)
     {
-        if ($time_interval < 0) {
+        if ($timeInterval < 0) {
             Worker::safeEcho(new Exception("bad time_interval"));
             return false;
         }
@@ -112,7 +112,7 @@ class Timer
         }
 
         if (self::$event) {
-            return $persistent ? self::$event->repeat($time_interval, $func, $args) : self::$event->delay($time_interval, $func, $args);
+            return $persistent ? self::$event->repeat($timeInterval, $func, $args) : self::$event->delay($timeInterval, $func, $args);
         }
         
         // If not workerman runtime just return.
@@ -129,14 +129,14 @@ class Timer
             \pcntl_alarm(1);
         }
 
-        $run_time = \time() + $time_interval;
-        if (!isset(self::$tasks[$run_time])) {
-            self::$tasks[$run_time] = [];
+        $runTime = \time() + $timeInterval;
+        if (!isset(self::$tasks[$runTime])) {
+            self::$tasks[$runTime] = [];
         }
 
         self::$timerId = self::$timerId == \PHP_INT_MAX ? 1 : ++self::$timerId;
         self::$status[self::$timerId] = true;
-        self::$tasks[$run_time][self::$timerId] = [$func, (array)$args, $persistent, $time_interval];
+        self::$tasks[$runTime][self::$timerId] = [$func, (array)$args, $persistent, $timeInterval];
 
         return self::$timerId;
     }
@@ -164,26 +164,26 @@ class Timer
             \pcntl_alarm(0);
             return;
         }
-        $time_now = \time();
-        foreach (self::$tasks as $run_time => $task_data) {
-            if ($time_now >= $run_time) {
-                foreach ($task_data as $index => $one_task) {
-                    $task_func     = $one_task[0];
-                    $task_args     = $one_task[1];
-                    $persistent    = $one_task[2];
-                    $time_interval = $one_task[3];
+        $timeNow = \time();
+        foreach (self::$tasks as $runTime => $taskData) {
+            if ($timeNow >= $runTime) {
+                foreach ($taskData as $index => $oneTask) {
+                    $taskFunc     = $oneTask[0];
+                    $taskArgs     = $oneTask[1];
+                    $persistent    = $oneTask[2];
+                    $timeInterval = $oneTask[3];
                     try {
-                        $task_func(...$task_args);
+                        $taskFunc(...$taskArgs);
                     } catch (\Throwable $e) {
                         Worker::safeEcho($e);
                     }
                     if($persistent && !empty(self::$status[$index])) {
-                        $new_run_time = \time() + $time_interval;
-                        if(!isset(self::$tasks[$new_run_time])) self::$tasks[$new_run_time] = [];
-                        self::$tasks[$new_run_time][$index] = [$task_func, (array)$task_args, $persistent, $time_interval];
+                        $newRunTime = \time() + $timeInterval;
+                        if(!isset(self::$tasks[$newRunTime])) self::$tasks[$newRunTime] = [];
+                        self::$tasks[$newRunTime][$index] = [$taskFunc, (array)$taskArgs, $persistent, $timeInterval];
                     }
                 }
-                unset(self::$tasks[$run_time]);
+                unset(self::$tasks[$runTime]);
             }
         }
     }
@@ -191,21 +191,21 @@ class Timer
     /**
      * Remove a timer.
      *
-     * @param mixed $timer_id
+     * @param mixed $timerId
      * @return bool
      */
-    public static function del($timer_id)
+    public static function del($timerId)
     {
         if (self::$event) {
-            return self::$event->deleteTimer($timer_id);
+            return self::$event->deleteTimer($timerId);
         }
 
-        foreach(self::$tasks as $run_time => $task_data) 
+        foreach(self::$tasks as $runTime => $taskData) 
         {
-            if(array_key_exists($timer_id, $task_data)) unset(self::$tasks[$run_time][$timer_id]);
+            if(array_key_exists($timerId, $taskData)) unset(self::$tasks[$runTime][$timerId]);
         }
 
-        if(array_key_exists($timer_id, self::$status)) unset(self::$status[$timer_id]);
+        if(array_key_exists($timerId, self::$status)) unset(self::$status[$timerId]);
 
         return true;
     }

Разлика између датотеке није приказан због своје велике величине
+ 230 - 230
src/Worker.php


Неке датотеке нису приказане због велике количине промена