فهرست منبع

Merge pull request #487 from joanhey/perf3

Performance optimizations
walkor 6 سال پیش
والد
کامیت
3dc9b5ba92
14فایلهای تغییر یافته به همراه198 افزوده شده و 195 حذف شده
  1. 3 3
      Autoloader.php
  2. 9 9
      Connection/AsyncTcpConnection.php
  3. 2 2
      Connection/AsyncUdpConnection.php
  4. 23 20
      Connection/TcpConnection.php
  5. 1 1
      Events/Ev.php
  6. 5 5
      Events/Libevent.php
  7. 6 6
      Events/Select.php
  8. 2 2
      Events/Swoole.php
  9. 7 8
      Lib/Timer.php
  10. 2 2
      Protocols/Http.php
  11. 11 11
      Protocols/Websocket.php
  12. 4 4
      Protocols/Ws.php
  13. 11 11
      WebServer.php
  14. 112 111
      Worker.php

+ 3 - 3
Autoloader.php

@@ -44,15 +44,15 @@ class Autoloader
      */
      */
     public static function loadByNamespace($name)
     public static function loadByNamespace($name)
     {
     {
-        $class_path = \str_replace('\\', DIRECTORY_SEPARATOR, $name);
+        $class_path = \str_replace('\\', \DIRECTORY_SEPARATOR, $name);
         if (\strpos($name, 'Workerman\\') === 0) {
         if (\strpos($name, 'Workerman\\') === 0) {
             $class_file = __DIR__ . \substr($class_path, \strlen('Workerman')) . '.php';
             $class_file = __DIR__ . \substr($class_path, \strlen('Workerman')) . '.php';
         } else {
         } else {
             if (self::$_autoloadRootPath) {
             if (self::$_autoloadRootPath) {
-                $class_file = self::$_autoloadRootPath . DIRECTORY_SEPARATOR . $class_path . '.php';
+                $class_file = self::$_autoloadRootPath . \DIRECTORY_SEPARATOR . $class_path . '.php';
             }
             }
             if (empty($class_file) || !\is_file($class_file)) {
             if (empty($class_file) || !\is_file($class_file)) {
-                $class_file = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . "$class_path.php";
+                $class_file = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . "$class_path.php";
             }
             }
         }
         }
 
 

+ 9 - 9
Connection/AsyncTcpConnection.php

@@ -16,7 +16,7 @@ namespace Workerman\Connection;
 use Workerman\Events\EventInterface;
 use Workerman\Events\EventInterface;
 use Workerman\Lib\Timer;
 use Workerman\Lib\Timer;
 use Workerman\Worker;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 
 /**
 /**
  * AsyncTcpConnection.
  * AsyncTcpConnection.
@@ -137,7 +137,7 @@ class AsyncTcpConnection extends TcpConnection
         }
         }
 
 
         $this->id = $this->_id = self::$_idRecorder++;
         $this->id = $this->_id = self::$_idRecorder++;
-        if(PHP_INT_MAX === self::$_idRecorder){
+        if(\PHP_INT_MAX === self::$_idRecorder){
             self::$_idRecorder = 0;
             self::$_idRecorder = 0;
         }
         }
         // Check application layer protocol class.
         // Check application layer protocol class.
@@ -179,14 +179,14 @@ class AsyncTcpConnection extends TcpConnection
             if ($this->_contextOption) {
             if ($this->_contextOption) {
                 $context = \stream_context_create($this->_contextOption);
                 $context = \stream_context_create($this->_contextOption);
                 $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
                 $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
-                    $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context);
+                    $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT, $context);
             } else {
             } else {
                 $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
                 $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
-                    $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT);
+                    $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT);
             }
             }
         } else {
         } else {
             $this->_socket = \stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
             $this->_socket = \stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
-                STREAM_CLIENT_ASYNC_CONNECT);
+                \STREAM_CLIENT_ASYNC_CONNECT);
         }
         }
         // If failed attempt to emit onError callback.
         // If failed attempt to emit onError callback.
         if (!$this->_socket || !\is_resource($this->_socket)) {
         if (!$this->_socket || !\is_resource($this->_socket)) {
@@ -202,7 +202,7 @@ class AsyncTcpConnection extends TcpConnection
         // Add socket to global event loop waiting connection is successfully established or faild.
         // Add socket to global event loop waiting connection is successfully established or faild.
         Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
         Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
         // For windows.
         // For windows.
-        if(DIRECTORY_SEPARATOR === '\\') {
+        if(\DIRECTORY_SEPARATOR === '\\') {
             Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection'));
             Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection'));
         }
         }
     }
     }
@@ -289,7 +289,7 @@ class AsyncTcpConnection extends TcpConnection
     public function checkConnection()
     public function checkConnection()
     {
     {
         // Remove EV_EXPECT for windows.
         // Remove EV_EXPECT for windows.
-        if(DIRECTORY_SEPARATOR === '\\') {
+        if(\DIRECTORY_SEPARATOR === '\\') {
             Worker::$globalEvent->del($this->_socket, EventInterface::EV_EXCEPT);
             Worker::$globalEvent->del($this->_socket, EventInterface::EV_EXCEPT);
         }
         }
 
 
@@ -311,8 +311,8 @@ class AsyncTcpConnection extends TcpConnection
             // Try to open keepalive for tcp and disable Nagle algorithm.
             // Try to open keepalive for tcp and disable Nagle algorithm.
             if (\function_exists('socket_import_stream') && $this->transport === 'tcp') {
             if (\function_exists('socket_import_stream') && $this->transport === 'tcp') {
                 $raw_socket = \socket_import_stream($this->_socket);
                 $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);
+                \socket_set_option($raw_socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
+                \socket_set_option($raw_socket, \SOL_TCP, \TCP_NODELAY, 1);
             }
             }
 
 
             // SSL handshake.
             // SSL handshake.

+ 2 - 2
Connection/AsyncUdpConnection.php

@@ -15,7 +15,7 @@ namespace Workerman\Connection;
 
 
 use Workerman\Events\EventInterface;
 use Workerman\Events\EventInterface;
 use Workerman\Worker;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 
 /**
 /**
  * AsyncTcpConnection.
  * AsyncTcpConnection.
@@ -176,7 +176,7 @@ class AsyncUdpConnection extends UdpConnection
         if ($this->_contextOption) {
         if ($this->_contextOption) {
             $context = \stream_context_create($this->_contextOption);
             $context = \stream_context_create($this->_contextOption);
             $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg,
             $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg,
-                30, STREAM_CLIENT_CONNECT, $context);
+                30, \STREAM_CLIENT_CONNECT, $context);
         } else {
         } else {
             $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg);
             $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg);
         }
         }

+ 23 - 20
Connection/TcpConnection.php

@@ -15,7 +15,7 @@ namespace Workerman\Connection;
 
 
 use Workerman\Events\EventInterface;
 use Workerman\Events\EventInterface;
 use Workerman\Worker;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 
 /**
 /**
  * TcpConnection.
  * TcpConnection.
@@ -294,7 +294,7 @@ class TcpConnection extends ConnectionInterface
     {
     {
         self::$statistics['connection_count']++;
         self::$statistics['connection_count']++;
         $this->id = $this->_id = self::$_idRecorder++;
         $this->id = $this->_id = self::$_idRecorder++;
-        if(self::$_idRecorder === PHP_INT_MAX){
+        if(self::$_idRecorder === \PHP_INT_MAX){
             self::$_idRecorder = 0;
             self::$_idRecorder = 0;
         }
         }
         $this->_socket = $socket;
         $this->_socket = $socket;
@@ -315,7 +315,7 @@ class TcpConnection extends ConnectionInterface
      *
      *
      * @param bool $raw_output
      * @param bool $raw_output
      *
      *
-     * @return int
+     * @return int|string
      */
      */
     public function getStatus($raw_output = true)
     public function getStatus($raw_output = true)
     {
     {
@@ -403,16 +403,16 @@ class TcpConnection extends ConnectionInterface
             // Check if the send buffer will be full.
             // Check if the send buffer will be full.
             $this->checkBufferWillFull();
             $this->checkBufferWillFull();
             return;
             return;
-        } else {
-            if ($this->bufferIsFull()) {
-                self::$statistics['send_fail']++;
-                return false;
-            }
+        }
 
 
-            $this->_sendBuffer .= $send_buffer;
-            // Check if the send buffer is full.
-            $this->checkBufferWillFull();
+        if ($this->bufferIsFull()) {
+            self::$statistics['send_fail']++;
+            return false;
         }
         }
+
+        $this->_sendBuffer .= $send_buffer;
+        // Check if the send buffer is full.
+        $this->checkBufferWillFull();
     }
     }
 
 
     /**
     /**
@@ -628,7 +628,7 @@ class TcpConnection extends ConnectionInterface
                         }
                         }
                     } // Wrong package.
                     } // Wrong package.
                     else {
                     else {
-                        Worker::safeEcho('error package. package_length=' . var_export($this->_currentPackageLength, true));
+                        Worker::safeEcho('Error package. package_length=' . \var_export($this->_currentPackageLength, true));
                         $this->destroy();
                         $this->destroy();
                         return;
                         return;
                     }
                     }
@@ -756,9 +756,9 @@ class TcpConnection extends ConnectionInterface
         }*/
         }*/
         
         
         if($async){
         if($async){
-            $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
+            $type = \STREAM_CRYPTO_METHOD_SSLv2_CLIENT | \STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
         }else{
         }else{
-            $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER;
+            $type = \STREAM_CRYPTO_METHOD_SSLv2_SERVER | \STREAM_CRYPTO_METHOD_SSLv23_SERVER;
         }
         }
         
         
         // Hidden error.
         // Hidden error.
@@ -838,14 +838,17 @@ class TcpConnection extends ConnectionInterface
             $this->destroy();
             $this->destroy();
             return;
             return;
         }
         }
+
         if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
         if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
             return;
             return;
-        } else {
-            if ($data !== null) {
-                $this->send($data, $raw);
-            }
-            $this->_status = self::STATUS_CLOSING;
         }
         }
+
+        if ($data !== null) {
+            $this->send($data, $raw);
+        }
+
+        $this->_status = self::STATUS_CLOSING;
+        
         if ($this->_sendBuffer === '') {
         if ($this->_sendBuffer === '') {
             $this->destroy();
             $this->destroy();
         } else {
         } else {
@@ -988,7 +991,7 @@ class TcpConnection extends ConnectionInterface
         self::$statistics['connection_count']--;
         self::$statistics['connection_count']--;
         if (Worker::getGracefulStop()) {
         if (Worker::getGracefulStop()) {
             if (!isset($mod)) {
             if (!isset($mod)) {
-                $mod = ceil((self::$statistics['connection_count'] + 1) / 3);
+                $mod = \ceil((self::$statistics['connection_count'] + 1) / 3);
             }
             }
 
 
             if (0 === self::$statistics['connection_count'] % $mod) {
             if (0 === self::$statistics['connection_count'] % $mod) {

+ 1 - 1
Events/Ev.php

@@ -13,7 +13,7 @@
 namespace Workerman\Events;
 namespace Workerman\Events;
 
 
 use Workerman\Worker;
 use Workerman\Worker;
-use EvWatcher;
+use \EvWatcher;
 
 
 /**
 /**
  * ev eventloop
  * ev eventloop

+ 5 - 5
Events/Libevent.php

@@ -54,7 +54,7 @@ class Libevent implements EventInterface
      */
      */
     public function __construct()
     public function __construct()
     {
     {
-        $this->_eventBase = event_base_new();
+        $this->_eventBase = \event_base_new();
     }
     }
 
 
     /**
     /**
@@ -65,8 +65,8 @@ class Libevent implements EventInterface
         switch ($flag) {
         switch ($flag) {
             case self::EV_SIGNAL:
             case self::EV_SIGNAL:
                 $fd_key                      = (int)$fd;
                 $fd_key                      = (int)$fd;
-                $real_flag                   = EV_SIGNAL | EV_PERSIST;
-                $this->_eventSignal[$fd_key] = event_new();
+                $real_flag                   = \EV_SIGNAL | \EV_PERSIST;
+                $this->_eventSignal[$fd_key] = \event_new();
                 if (!\event_set($this->_eventSignal[$fd_key], $fd, $real_flag, $func, null)) {
                 if (!\event_set($this->_eventSignal[$fd_key], $fd, $real_flag, $func, null)) {
                     return false;
                     return false;
                 }
                 }
@@ -81,7 +81,7 @@ class Libevent implements EventInterface
             case self::EV_TIMER_ONCE:
             case self::EV_TIMER_ONCE:
                 $event    = \event_new();
                 $event    = \event_new();
                 $timer_id = (int)$event;
                 $timer_id = (int)$event;
-                if (!\event_set($event, 0, EV_TIMEOUT, array($this, 'timerCallback'), $timer_id)) {
+                if (!\event_set($event, 0, \EV_TIMEOUT, array($this, 'timerCallback'), $timer_id)) {
                     return false;
                     return false;
                 }
                 }
 
 
@@ -98,7 +98,7 @@ class Libevent implements EventInterface
 
 
             default :
             default :
                 $fd_key    = (int)$fd;
                 $fd_key    = (int)$fd;
-                $real_flag = $flag === self::EV_READ ? EV_READ | EV_PERSIST : EV_WRITE | EV_PERSIST;
+                $real_flag = $flag === self::EV_READ ? \EV_READ | \EV_PERSIST : \EV_WRITE | \EV_PERSIST;
 
 
                 $event = \event_new();
                 $event = \event_new();
 
 

+ 6 - 6
Events/Select.php

@@ -96,8 +96,8 @@ class Select implements EventInterface
     public function __construct()
     public function __construct()
     {
     {
         // Create a pipeline and put into the collection of the read to read the descriptor to avoid empty polling.
         // Create a pipeline and put into the collection of the read to read the descriptor to avoid empty polling.
-        $this->channel = \stream_socket_pair(DIRECTORY_SEPARATOR === '/' ? STREAM_PF_UNIX : STREAM_PF_INET,
-            STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
+        $this->channel = \stream_socket_pair(\DIRECTORY_SEPARATOR === '/' ? \STREAM_PF_UNIX : \STREAM_PF_INET,
+            \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP);
         if($this->channel) {
         if($this->channel) {
             \stream_set_blocking($this->channel[0], 0);
             \stream_set_blocking($this->channel[0], 0);
             $this->_readFds[0] = $this->channel[0];
             $this->_readFds[0] = $this->channel[0];
@@ -118,7 +118,7 @@ class Select implements EventInterface
                 $count = $flag === self::EV_READ ? \count($this->_readFds) : \count($this->_writeFds);
                 $count = $flag === self::EV_READ ? \count($this->_readFds) : \count($this->_writeFds);
                 if ($count >= 1024) {
                 if ($count >= 1024) {
                     echo "Warning: system call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.\n";
                     echo "Warning: system call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.\n";
-                } else if (DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
+                } else if (\DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
                     echo "Warning: system call select exceeded the maximum number of connections 256.\n";
                     echo "Warning: system call select exceeded the maximum number of connections 256.\n";
                 }
                 }
                 $fd_key                           = (int)$fd;
                 $fd_key                           = (int)$fd;
@@ -136,7 +136,7 @@ class Select implements EventInterface
                 break;
                 break;
             case self::EV_SIGNAL:
             case self::EV_SIGNAL:
                 // Windows not support signal.
                 // Windows not support signal.
-                if(DIRECTORY_SEPARATOR !== '/') {
+                if(\DIRECTORY_SEPARATOR !== '/') {
                     return false;
                     return false;
                 }
                 }
                 $fd_key                              = (int)$fd;
                 $fd_key                              = (int)$fd;
@@ -196,7 +196,7 @@ class Select implements EventInterface
                 }
                 }
                 return true;
                 return true;
             case self::EV_SIGNAL:
             case self::EV_SIGNAL:
-                if(DIRECTORY_SEPARATOR !== '/') {
+                if(\DIRECTORY_SEPARATOR !== '/') {
                     return false;
                     return false;
                 }
                 }
                 unset($this->_signalEvents[$fd_key]);
                 unset($this->_signalEvents[$fd_key]);
@@ -263,7 +263,7 @@ class Select implements EventInterface
     public function loop()
     public function loop()
     {
     {
         while (1) {
         while (1) {
-            if(DIRECTORY_SEPARATOR === '/') {
+            if(\DIRECTORY_SEPARATOR === '/') {
                 // Calls signal handlers for pending signals
                 // Calls signal handlers for pending signals
                 \pcntl_signal_dispatch();
                 \pcntl_signal_dispatch();
             }
             }

+ 2 - 2
Events/Swoole.php

@@ -57,7 +57,7 @@ class Swoole implements EventInterface
             case self::EV_TIMER:
             case self::EV_TIMER:
             case self::EV_TIMER_ONCE:
             case self::EV_TIMER_ONCE:
                 $method = self::EV_TIMER === $flag ? 'tick' : 'after';
                 $method = self::EV_TIMER === $flag ? 'tick' : 'after';
-                if ($this->mapId > PHP_INT_MAX) {
+                if ($this->mapId > \PHP_INT_MAX) {
                     $this->mapId = 0;
                     $this->mapId = 0;
                 }
                 }
                 $mapId = $this->mapId++;
                 $mapId = $this->mapId++;
@@ -67,7 +67,7 @@ class Swoole implements EventInterface
                         // EV_TIMER_ONCE
                         // EV_TIMER_ONCE
                         if (! isset($timer_id)) {
                         if (! isset($timer_id)) {
                             // may be deleted in $func
                             // may be deleted in $func
-                            if (array_key_exists($mapId, $this->_timerOnceMap)) {
+                            if (\array_key_exists($mapId, $this->_timerOnceMap)) {
                                 $timer_id = $this->_timerOnceMap[$mapId];
                                 $timer_id = $this->_timerOnceMap[$mapId];
                                 unset($this->_timer[$timer_id],
                                 unset($this->_timer[$timer_id],
                                     $this->_timerOnceMap[$mapId]);
                                     $this->_timerOnceMap[$mapId]);

+ 7 - 8
Lib/Timer.php

@@ -15,7 +15,7 @@ namespace Workerman\Lib;
 
 
 use Workerman\Events\EventInterface;
 use Workerman\Events\EventInterface;
 use Workerman\Worker;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 
 /**
 /**
  * Timer.
  * Timer.
@@ -50,14 +50,14 @@ class Timer
      * @param EventInterface $event
      * @param EventInterface $event
      * @return void
      * @return void
      */
      */
-    public static function init($event = null)
+    public static function init(EventInterface $event = null)
     {
     {
         if ($event) {
         if ($event) {
             self::$_event = $event;
             self::$_event = $event;
-        } else {
-            if (\function_exists('pcntl_signal')) {
-                \pcntl_signal(SIGALRM, array('\Workerman\Lib\Timer', 'signalHandle'), false);
-            }
+            return;
+        }
+        if (\function_exists('pcntl_signal')) {
+            \pcntl_signal(\SIGALRM, array('\Workerman\Lib\Timer', 'signalHandle'), false);
         }
         }
     }
     }
 
 
@@ -108,8 +108,7 @@ class Timer
             \pcntl_alarm(1);
             \pcntl_alarm(1);
         }
         }
 
 
-        $time_now = \time();
-        $run_time = $time_now + $time_interval;
+        $run_time = \time() + $time_interval;
         if (!isset(self::$_tasks[$run_time])) {
         if (!isset(self::$_tasks[$run_time])) {
             self::$_tasks[$run_time] = array();
             self::$_tasks[$run_time] = array();
         }
         }

+ 2 - 2
Protocols/Http.php

@@ -86,7 +86,7 @@ class Http
     public static function decode($recv_buffer, TcpConnection $connection)
     public static function decode($recv_buffer, TcpConnection $connection)
     {
     {
         // Init.
         // Init.
-        $_POST                         = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
+        $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
         $GLOBALS['HTTP_RAW_POST_DATA'] = '';
         $GLOBALS['HTTP_RAW_POST_DATA'] = '';
         // Clear cache.
         // Clear cache.
         HttpCache::reset();
         HttpCache::reset();
@@ -202,7 +202,7 @@ class Http
         $GLOBALS['HTTP_RAW_REQUEST_DATA'] = $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
         $GLOBALS['HTTP_RAW_REQUEST_DATA'] = $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
 
 
         // QUERY_STRING
         // QUERY_STRING
-        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
+        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], \PHP_URL_QUERY);
         if ($_SERVER['QUERY_STRING']) {
         if ($_SERVER['QUERY_STRING']) {
             // $GET
             // $GET
             \parse_str($_SERVER['QUERY_STRING'], $_GET);
             \parse_str($_SERVER['QUERY_STRING'], $_GET);

+ 11 - 11
Protocols/Websocket.php

@@ -233,7 +233,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
     public static function encode($buffer, ConnectionInterface $connection)
     public static function encode($buffer, ConnectionInterface $connection)
     {
     {
         if (!is_scalar($buffer)) {
         if (!is_scalar($buffer)) {
-            throw new \Exception("You can't send(" . gettype($buffer) . ") to client, you need to convert it to a string. ");
+            throw new \Exception("You can't send(" . \gettype($buffer) . ") to client, you need to convert it to a string. ");
         }
         }
         $len = \strlen($buffer);
         $len = \strlen($buffer);
         if (empty($connection->websocketType)) {
         if (empty($connection->websocketType)) {
@@ -355,19 +355,19 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             if (\preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
             if (\preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
                 $Sec_WebSocket_Key = $match[1];
                 $Sec_WebSocket_Key = $match[1];
             } else {
             } else {
-                $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powerd by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
+                $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powered by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
                     true);
                     true);
                 $connection->close();
                 $connection->close();
                 return 0;
                 return 0;
             }
             }
             // Calculation websocket key.
             // Calculation websocket key.
-            $new_key = \base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
+            $new_key = \base64_encode(\sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
             // Handshake response data.
             // Handshake response data.
-            $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
-            $handshake_message .= "Upgrade: websocket\r\n";
-            $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
-            $handshake_message .= "Connection: Upgrade\r\n";
-            $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n";
+            $handshake_message = "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";
 
 
             // Websocket data buffer.
             // Websocket data buffer.
             $connection->websocketDataBuffer = '';
             $connection->websocketDataBuffer = '';
@@ -440,7 +440,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             return 0;
             return 0;
         }
         }
         // Bad websocket handshake request.
         // Bad websocket handshake request.
-        $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powerd by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
+        $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powered by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
             true);
             true);
         $connection->close();
         $connection->close();
         return 0;
         return 0;
@@ -472,7 +472,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 continue;
                 continue;
             }
             }
             list($key, $value)       = \explode(':', $content, 2);
             list($key, $value)       = \explode(':', $content, 2);
-            $key                     = \str_replace('-', '_', strtoupper($key));
+            $key                     = \str_replace('-', '_', \strtoupper($key));
             $value                   = \trim($value);
             $value                   = \trim($value);
             $_SERVER['HTTP_' . $key] = $value;
             $_SERVER['HTTP_' . $key] = $value;
             switch ($key) {
             switch ($key) {
@@ -492,7 +492,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
         }
         }
 
 
         // QUERY_STRING
         // QUERY_STRING
-        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
+        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], \PHP_URL_QUERY);
         if ($_SERVER['QUERY_STRING']) {
         if ($_SERVER['QUERY_STRING']) {
             // $GET
             // $GET
             \parse_str($_SERVER['QUERY_STRING'], $_GET);
             \parse_str($_SERVER['QUERY_STRING'], $_GET);

+ 4 - 4
Protocols/Ws.php

@@ -47,7 +47,7 @@ class Ws
     public static function input($buffer, ConnectionInterface $connection)
     public static function input($buffer, ConnectionInterface $connection)
     {
     {
         if (empty($connection->handshakeStep)) {
         if (empty($connection->handshakeStep)) {
-            Worker::safeEcho("recv data before handshake. Buffer:" . bin2hex($buffer) . "\n");
+            Worker::safeEcho("recv data before handshake. Buffer:" . \bin2hex($buffer) . "\n");
             return false;
             return false;
         }
         }
         // Recv handshake response
         // Recv handshake response
@@ -365,7 +365,7 @@ class Ws
         $port = $connection->getRemotePort();
         $port = $connection->getRemotePort();
         $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
         $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
         // Handshake header.
         // Handshake header.
-        $connection->websocketSecKey = \base64_encode(md5(\mt_rand(), true));
+        $connection->websocketSecKey = \base64_encode(\md5(\mt_rand(), true));
         $user_header = isset($connection->headers) ? $connection->headers :
         $user_header = isset($connection->headers) ? $connection->headers :
             (isset($connection->wsHttpHeader) ? $connection->wsHttpHeader : null);
             (isset($connection->wsHttpHeader) ? $connection->wsHttpHeader : null);
         $user_header_str = '';
         $user_header_str = '';
@@ -407,7 +407,7 @@ class Ws
         if ($pos) {
         if ($pos) {
             //checking Sec-WebSocket-Accept
             //checking Sec-WebSocket-Accept
             if (\preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
             if (\preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
-                if ($match[1] !== \base64_encode(sha1($connection->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
+                if ($match[1] !== \base64_encode(\sha1($connection->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
                     Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . \substr($buffer, 0, $pos) . "\n");
                     Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . \substr($buffer, 0, $pos) . "\n");
                     $connection->close();
                     $connection->close();
                     return 0;
                     return 0;
@@ -466,7 +466,7 @@ class Ws
     }
     }
 
 
     public static function WSGetServerProtocol($connection) {
     public static function WSGetServerProtocol($connection) {
-	return (\property_exists($connection, 'WSServerProtocol')?$connection->WSServerProtocol:null);
+	return (\property_exists($connection, 'WSServerProtocol') ? $connection->WSServerProtocol : null);
     }
     }
 
 
 }
 }

+ 11 - 11
WebServer.php

@@ -53,7 +53,7 @@ class WebServer extends Worker
      */
      */
     public function addRoot($domain, $config)
     public function addRoot($domain, $config)
     {
     {
-        if (is_string($config)) {
+        if (\is_string($config)) {
             $config = array('root' => $config);
             $config = array('root' => $config);
         }
         }
         $this->serverRoot[$domain] = $config;
         $this->serverRoot[$domain] = $config;
@@ -126,7 +126,7 @@ class WebServer extends Worker
             $this->log("$mime_file mime.type file not fond");
             $this->log("$mime_file mime.type file not fond");
             return;
             return;
         }
         }
-        $items = \file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+        $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
         if (!\is_array($items)) {
         if (!\is_array($items)) {
             $this->log("get $mime_file mime.type content fail");
             $this->log("get $mime_file mime.type content fail");
             return;
             return;
@@ -172,7 +172,7 @@ class WebServer extends Worker
             $workerman_file_extension = 'php';
             $workerman_file_extension = 'php';
         }
         }
 
 
-        $workerman_siteConfig = isset($this->serverRoot[$_SERVER['SERVER_NAME']]) ? $this->serverRoot[$_SERVER['SERVER_NAME']] : current($this->serverRoot);
+        $workerman_siteConfig = isset($this->serverRoot[$_SERVER['SERVER_NAME']]) ? $this->serverRoot[$_SERVER['SERVER_NAME']] : \current($this->serverRoot);
 		$workerman_root_dir = $workerman_siteConfig['root'];
 		$workerman_root_dir = $workerman_siteConfig['root'];
         $workerman_file = "$workerman_root_dir/$workerman_path";
         $workerman_file = "$workerman_root_dir/$workerman_path";
 		if(isset($workerman_siteConfig['additionHeader'])){
 		if(isset($workerman_siteConfig['additionHeader'])){
@@ -205,7 +205,7 @@ class WebServer extends Worker
 
 
             // Request php file.
             // Request php file.
             if ($workerman_file_extension === 'php') {
             if ($workerman_file_extension === 'php') {
-                $workerman_cwd = getcwd();
+                $workerman_cwd = \getcwd();
                 \chdir($workerman_root_dir);
                 \chdir($workerman_root_dir);
                 \ini_set('display_errors', 'off');
                 \ini_set('display_errors', 'off');
                 \ob_start();
                 \ob_start();
@@ -237,7 +237,7 @@ class WebServer extends Worker
         } else {
         } else {
             // 404
             // 404
             Http::header("HTTP/1.1 404 Not Found");
             Http::header("HTTP/1.1 404 Not Found");
-			if(isset($workerman_siteConfig['custom404']) && file_exists($workerman_siteConfig['custom404'])){
+			if(isset($workerman_siteConfig['custom404']) && \file_exists($workerman_siteConfig['custom404'])){
 				$html404 = \file_get_contents($workerman_siteConfig['custom404']);
 				$html404 = \file_get_contents($workerman_siteConfig['custom404']);
 			}else{
 			}else{
 				$html404 = '<html><head><title>404 File not found</title></head><body><center><h3>404 Not Found</h3></center></body></html>';
 				$html404 = '<html><head><title>404 File not found</title></head><body><center><h3>404 Not Found</h3></center></body></html>';
@@ -254,7 +254,7 @@ class WebServer extends Worker
     public static function sendFile($connection, $file_path)
     public static function sendFile($connection, $file_path)
     {
     {
         // Check 304.
         // Check 304.
-        $info = stat($file_path);
+        $info = \stat($file_path);
         $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
         $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
         if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info) {
         if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info) {
             // Http 304.
             // Http 304.
@@ -283,12 +283,12 @@ class WebServer extends Worker
         if (isset(self::$mimeTypeMap[$extension])) {
         if (isset(self::$mimeTypeMap[$extension])) {
             $header .= "Content-Type: " . self::$mimeTypeMap[$extension] . "\r\n";
             $header .= "Content-Type: " . self::$mimeTypeMap[$extension] . "\r\n";
         } else {
         } else {
-            $header .= "Content-Type: application/octet-stream\r\n";
-            $header .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";
+            $header .= "Content-Type: application/octet-stream\r\n"
+                    ."Content-Disposition: attachment; filename=\"$file_name\"\r\n";
         }
         }
-        $header .= "Connection: keep-alive\r\n";
-        $header .= $modified_time;
-        $header .= "Content-Length: $file_size\r\n\r\n";
+        $header .= "Connection: keep-alive\r\n"
+                .$modified_time
+                ."Content-Length: $file_size\r\n\r\n";
         $trunk_limit_size = 1024*1024;
         $trunk_limit_size = 1024*1024;
         if ($file_size < $trunk_limit_size) {
         if ($file_size < $trunk_limit_size) {
             return $connection->send($header.\file_get_contents($file_path), true);
             return $connection->send($header.\file_get_contents($file_path), true);

+ 112 - 111
Worker.php

@@ -20,7 +20,7 @@ use Workerman\Connection\TcpConnection;
 use Workerman\Connection\UdpConnection;
 use Workerman\Connection\UdpConnection;
 use Workerman\Lib\Timer;
 use Workerman\Lib\Timer;
 use Workerman\Events\Select;
 use Workerman\Events\Select;
-use Exception;
+use \Exception;
 
 
 /**
 /**
  * Worker class
  * Worker class
@@ -275,7 +275,7 @@ class Worker
     /**
     /**
      * Global event loop.
      * Global event loop.
      *
      *
-     * @var Events\EventInterface
+     * @var EventInterface
      */
      */
     public static $globalEvent = null;
     public static $globalEvent = null;
 
 
@@ -483,21 +483,21 @@ class Worker
      * @var array
      * @var array
      */
      */
     protected static $_errorType = array(
     protected static $_errorType = array(
-        E_ERROR             => 'E_ERROR',             // 1
-        E_WARNING           => 'E_WARNING',           // 2
-        E_PARSE             => 'E_PARSE',             // 4
-        E_NOTICE            => 'E_NOTICE',            // 8
-        E_CORE_ERROR        => 'E_CORE_ERROR',        // 16
-        E_CORE_WARNING      => 'E_CORE_WARNING',      // 32
-        E_COMPILE_ERROR     => 'E_COMPILE_ERROR',     // 64
-        E_COMPILE_WARNING   => 'E_COMPILE_WARNING',   // 128
-        E_USER_ERROR        => 'E_USER_ERROR',        // 256
-        E_USER_WARNING      => 'E_USER_WARNING',      // 512
-        E_USER_NOTICE       => 'E_USER_NOTICE',       // 1024
-        E_STRICT            => 'E_STRICT',            // 2048
-        E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', // 4096
-        E_DEPRECATED        => 'E_DEPRECATED',        // 8192
-        E_USER_DEPRECATED   => 'E_USER_DEPRECATED'   // 16384
+        \E_ERROR             => 'E_ERROR',             // 1
+        \E_WARNING           => 'E_WARNING',           // 2
+        \E_PARSE             => 'E_PARSE',             // 4
+        \E_NOTICE            => 'E_NOTICE',            // 8
+        \E_CORE_ERROR        => 'E_CORE_ERROR',        // 16
+        \E_CORE_WARNING      => 'E_CORE_WARNING',      // 32
+        \E_COMPILE_ERROR     => 'E_COMPILE_ERROR',     // 64
+        \E_COMPILE_WARNING   => 'E_COMPILE_WARNING',   // 128
+        \E_USER_ERROR        => 'E_USER_ERROR',        // 256
+        \E_USER_WARNING      => 'E_USER_WARNING',      // 512
+        \E_USER_NOTICE       => 'E_USER_NOTICE',       // 1024
+        \E_STRICT            => 'E_STRICT',            // 2048
+        \E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', // 4096
+        \E_DEPRECATED        => 'E_DEPRECATED',        // 8192
+        \E_USER_DEPRECATED   => 'E_USER_DEPRECATED'   // 16384
     );
     );
 
 
     /**
     /**
@@ -552,7 +552,7 @@ class Worker
         if (\PHP_SAPI !== 'cli') {
         if (\PHP_SAPI !== 'cli') {
             exit("Only run in command line mode \n");
             exit("Only run in command line mode \n");
         }
         }
-        if (DIRECTORY_SEPARATOR === '\\') {
+        if (\DIRECTORY_SEPARATOR === '\\') {
             self::$_OS = OS_TYPE_WINDOWS;
             self::$_OS = OS_TYPE_WINDOWS;
         }
         }
     }
     }
@@ -629,7 +629,7 @@ class Worker
     protected static function unlock()
     protected static function unlock()
     {
     {
         $fd = \fopen(static::$_startFile, 'r');
         $fd = \fopen(static::$_startFile, 'r');
-        $fd && flock($fd, LOCK_UN);
+        $fd && flock($fd, \LOCK_UN);
     }
     }
 
 
     /**
     /**
@@ -746,18 +746,18 @@ class Worker
         }
         }
         if (static::$_OS !== OS_TYPE_LINUX) {
         if (static::$_OS !== OS_TYPE_LINUX) {
             static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
             static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
-            static::safeEcho('Workerman version:'. static::VERSION. '          PHP version:'. PHP_VERSION. "\r\n");
+            static::safeEcho('Workerman version:'. static::VERSION. '          PHP version:'. \PHP_VERSION. "\r\n");
             static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
             static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
             static::safeEcho("worker               listen                              processes status\r\n");
             static::safeEcho("worker               listen                              processes status\r\n");
             return;
             return;
         }
         }
 
 
         //show version
         //show version
-        $line_version = 'Workerman version:' . static::VERSION . \str_pad('PHP version:', 22, ' ', STR_PAD_LEFT) . PHP_VERSION . PHP_EOL;
+        $line_version = 'Workerman version:' . static::VERSION . \str_pad('PHP version:', 22, ' ', \STR_PAD_LEFT) . \PHP_VERSION . \PHP_EOL;
         !\defined('LINE_VERSIOIN_LENGTH') && \define('LINE_VERSIOIN_LENGTH', \strlen($line_version));
         !\defined('LINE_VERSIOIN_LENGTH') && \define('LINE_VERSIOIN_LENGTH', \strlen($line_version));
         $total_length = static::getSingleLineTotalLength();
         $total_length = static::getSingleLineTotalLength();
-        $line_one = '<n>' . \str_pad('<w> WORKERMAN </w>', $total_length + \strlen('<w></w>'), '-', STR_PAD_BOTH) . '</n>'. PHP_EOL;
-        $line_two = \str_pad('<w> WORKERS </w>' , $total_length  + \strlen('<w></w>'), '-', STR_PAD_BOTH) . PHP_EOL;
+        $line_one = '<n>' . \str_pad('<w> WORKERMAN </w>', $total_length + \strlen('<w></w>'), '-', \STR_PAD_BOTH) . '</n>'. \PHP_EOL;
+        $line_two = \str_pad('<w> WORKERS </w>' , $total_length  + \strlen('<w></w>'), '-', \STR_PAD_BOTH) . \PHP_EOL;
         static::safeEcho($line_one . $line_version . $line_two);
         static::safeEcho($line_one . $line_version . $line_two);
 
 
         //Show title
         //Show title
@@ -768,7 +768,7 @@ class Worker
             $column_name === 'socket' && $column_name = 'listen';
             $column_name === 'socket' && $column_name = 'listen';
             $title.= "<w>{$column_name}</w>"  .  \str_pad('', static::$$key + static::UI_SAFE_LENGTH - \strlen($column_name));
             $title.= "<w>{$column_name}</w>"  .  \str_pad('', static::$$key + static::UI_SAFE_LENGTH - \strlen($column_name));
         }
         }
-        $title && static::safeEcho($title . PHP_EOL);
+        $title && static::safeEcho($title . \PHP_EOL);
 
 
         //Show content
         //Show content
         foreach (static::$_workers as $worker) {
         foreach (static::$_workers as $worker) {
@@ -779,11 +779,11 @@ class Worker
                 $place_holder_length = !empty($matches) ? \strlen(\implode('', $matches[0])) : 0;
                 $place_holder_length = !empty($matches) ? \strlen(\implode('', $matches[0])) : 0;
                 $content .= \str_pad($worker->{$prop}, static::$$key + static::UI_SAFE_LENGTH + $place_holder_length);
                 $content .= \str_pad($worker->{$prop}, static::$$key + static::UI_SAFE_LENGTH + $place_holder_length);
             }
             }
-            $content && static::safeEcho($content . PHP_EOL);
+            $content && static::safeEcho($content . \PHP_EOL);
         }
         }
 
 
         //Show last line
         //Show last line
-        $line_last = \str_pad('', static::getSingleLineTotalLength(), '-') . PHP_EOL;
+        $line_last = \str_pad('', static::getSingleLineTotalLength(), '-') . \PHP_EOL;
         !empty($content) && static::safeEcho($line_last);
         !empty($content) && static::safeEcho($line_last);
 
 
         if (static::$daemonize) {
         if (static::$daemonize) {
@@ -929,19 +929,19 @@ class Worker
                 // Waiting amoment.
                 // Waiting amoment.
                 \usleep(500000);
                 \usleep(500000);
                 // Display statisitcs data from a disk file.
                 // Display statisitcs data from a disk file.
-                if(is_readable(static::$_statisticsFile)) {
-                    readfile(static::$_statisticsFile);
+                if(\is_readable(static::$_statisticsFile)) {
+                    \readfile(static::$_statisticsFile);
                 }
                 }
                 exit(0);
                 exit(0);
             case 'restart':
             case 'restart':
             case 'stop':
             case 'stop':
                 if ($command2 === '-g') {
                 if ($command2 === '-g') {
                     static::$_gracefulStop = true;
                     static::$_gracefulStop = true;
-                    $sig = SIGTERM;
+                    $sig = \SIGTERM;
                     static::log("Workerman[$start_file] is gracefully stopping ...");
                     static::log("Workerman[$start_file] is gracefully stopping ...");
                 } else {
                 } else {
                     static::$_gracefulStop = false;
                     static::$_gracefulStop = false;
-                    $sig = SIGINT;
+                    $sig = \SIGINT;
                     static::log("Workerman[$start_file] is stopping ...");
                     static::log("Workerman[$start_file] is stopping ...");
                 }
                 }
                 // Send stop signal to master process.
                 // Send stop signal to master process.
@@ -975,9 +975,9 @@ class Worker
                 break;
                 break;
             case 'reload':
             case 'reload':
                 if($command2 === '-g'){
                 if($command2 === '-g'){
-                    $sig = SIGQUIT;
+                    $sig = \SIGQUIT;
                 }else{
                 }else{
-                    $sig = SIGUSR1;
+                    $sig = \SIGUSR1;
                 }
                 }
                 \posix_kill($master_pid, $sig);
                 \posix_kill($master_pid, $sig);
                 exit;
                 exit;
@@ -997,10 +997,10 @@ class Worker
     protected static function formatStatusData()
     protected static function formatStatusData()
     {
     {
         static $total_request_cache = array();
         static $total_request_cache = array();
-        if (!is_readable(static::$_statisticsFile)) {
+        if (!\is_readable(static::$_statisticsFile)) {
             return '';
             return '';
         }
         }
-        $info = file(static::$_statisticsFile, FILE_IGNORE_NEW_LINES);
+        $info = \file(static::$_statisticsFile, \FILE_IGNORE_NEW_LINES);
         if (!$info) {
         if (!$info) {
             return '';
             return '';
         }
         }
@@ -1031,7 +1031,7 @@ class Worker
                 $pid = $pid_math[0];
                 $pid = $pid_math[0];
                 $data_waiting_sort[$pid] = $value;
                 $data_waiting_sort[$pid] = $value;
                 if(\preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
                 if(\preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
-                    $total_memory += \intval(str_ireplace('M','',$match[1]));
+                    $total_memory += \intval(\str_ireplace('M','',$match[1]));
                     $maxLen1 = \max($maxLen1,\strlen($match[2]));
                     $maxLen1 = \max($maxLen1,\strlen($match[2]));
                     $maxLen2 = \max($maxLen2,\strlen($match[3]));
                     $maxLen2 = \max($maxLen2,\strlen($match[3]));
                     $total_connections += \intval($match[4]);
                     $total_connections += \intval($match[4]);
@@ -1083,19 +1083,19 @@ class Worker
             return;
             return;
         }
         }
         // stop
         // stop
-        \pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
         // graceful stop
         // graceful stop
-        \pcntl_signal(SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
         // reload
         // reload
-        \pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
         // graceful reload
         // graceful reload
-        \pcntl_signal(SIGQUIT, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGQUIT, array('\Workerman\Worker', 'signalHandler'), false);
         // status
         // status
-        \pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
         // connection status
         // connection status
-        \pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
         // ignore
         // ignore
-        \pcntl_signal(SIGPIPE, SIG_IGN, false);
+        \pcntl_signal(\SIGPIPE, \SIG_IGN, false);
     }
     }
 
 
     /**
     /**
@@ -1109,29 +1109,29 @@ class Worker
             return;
             return;
         }
         }
         // uninstall stop signal handler
         // uninstall stop signal handler
-        \pcntl_signal(SIGINT, SIG_IGN, false);
+        \pcntl_signal(\SIGINT, \SIG_IGN, false);
         // uninstall graceful stop signal handler
         // uninstall graceful stop signal handler
-        \pcntl_signal(SIGTERM, SIG_IGN, false);
+        \pcntl_signal(\SIGTERM, \SIG_IGN, false);
         // uninstall reload signal handler
         // uninstall reload signal handler
-        \pcntl_signal(SIGUSR1, SIG_IGN, false);
+        \pcntl_signal(\SIGUSR1, \SIG_IGN, false);
         // uninstall graceful reload signal handler
         // uninstall graceful reload signal handler
-        \pcntl_signal(SIGQUIT, SIG_IGN, false);
+        \pcntl_signal(\SIGQUIT, \SIG_IGN, false);
         // uninstall status signal handler
         // uninstall status signal handler
-        \pcntl_signal(SIGUSR2, SIG_IGN, false);
+        \pcntl_signal(\SIGUSR2, \SIG_IGN, false);
         // uninstall connections status signal handler
         // uninstall connections status signal handler
-        \pcntl_signal(SIGIO, SIG_IGN, false);
+        \pcntl_signal(\SIGIO, \SIG_IGN, false);
         // reinstall stop signal handler
         // reinstall stop signal handler
-        static::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
         // reinstall graceful stop signal handler
         // reinstall graceful stop signal handler
-        static::$globalEvent->add(SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
         // reinstall reload signal handler
         // reinstall reload signal handler
-        static::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
         // reinstall graceful reload signal handler
         // reinstall graceful reload signal handler
-        static::$globalEvent->add(SIGQUIT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGQUIT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
         // reinstall status signal handler
         // reinstall status signal handler
-        static::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
         // reinstall connection status signal handler
         // reinstall connection status signal handler
-        static::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
     }
     }
 
 
     /**
     /**
@@ -1143,19 +1143,19 @@ class Worker
     {
     {
         switch ($signal) {
         switch ($signal) {
             // Stop.
             // Stop.
-            case SIGINT:
+            case \SIGINT:
                 static::$_gracefulStop = false;
                 static::$_gracefulStop = false;
                 static::stopAll();
                 static::stopAll();
                 break;
                 break;
             // Graceful stop.
             // Graceful stop.
-            case SIGTERM:
+            case \SIGTERM:
                 static::$_gracefulStop = true;
                 static::$_gracefulStop = true;
                 static::stopAll();
                 static::stopAll();
                 break;
                 break;
             // Reload.
             // Reload.
-            case SIGQUIT:
-            case SIGUSR1:
-                if($signal === SIGQUIT){
+            case \SIGQUIT:
+            case \SIGUSR1:
+                if($signal === \SIGQUIT){
                     static::$_gracefulStop = true;
                     static::$_gracefulStop = true;
                 }else{
                 }else{
                     static::$_gracefulStop = false;
                     static::$_gracefulStop = false;
@@ -1164,11 +1164,11 @@ class Worker
                 static::reload();
                 static::reload();
                 break;
                 break;
             // Show status.
             // Show status.
-            case SIGUSR2:
+            case \SIGUSR2:
                 static::writeStatisticsToStatusFile();
                 static::writeStatisticsToStatusFile();
                 break;
                 break;
             // Show connection status.
             // Show connection status.
-            case SIGIO:
+            case \SIGIO:
                 static::writeConnectionsStatisticsToStatusFile();
                 static::writeConnectionsStatisticsToStatusFile();
                 break;
                 break;
         }
         }
@@ -1187,17 +1187,17 @@ class Worker
         \umask(0);
         \umask(0);
         $pid = \pcntl_fork();
         $pid = \pcntl_fork();
         if (-1 === $pid) {
         if (-1 === $pid) {
-            throw new Exception('fork fail');
+            throw new Exception('Fork fail');
         } elseif ($pid > 0) {
         } elseif ($pid > 0) {
             exit(0);
             exit(0);
         }
         }
         if (-1 === \posix_setsid()) {
         if (-1 === \posix_setsid()) {
-            throw new Exception("setsid fail");
+            throw new Exception("Setsid fail");
         }
         }
         // Fork again avoid SVR4 system regain the control of terminal.
         // Fork again avoid SVR4 system regain the control of terminal.
         $pid = \pcntl_fork();
         $pid = \pcntl_fork();
         if (-1 === $pid) {
         if (-1 === $pid) {
-            throw new Exception("fork fail");
+            throw new Exception("Fork fail");
         } elseif (0 !== $pid) {
         } elseif (0 !== $pid) {
             exit(0);
             exit(0);
         }
         }
@@ -1220,17 +1220,18 @@ class Worker
             \set_error_handler(function(){});
             \set_error_handler(function(){});
             \fclose($STDOUT);
             \fclose($STDOUT);
             \fclose($STDERR);
             \fclose($STDERR);
-            \fclose(STDOUT);
-            \fclose(STDERR);
+            \fclose(\STDOUT);
+            \fclose(\STDERR);
             $STDOUT = \fopen(static::$stdoutFile, "a");
             $STDOUT = \fopen(static::$stdoutFile, "a");
             $STDERR = \fopen(static::$stdoutFile, "a");
             $STDERR = \fopen(static::$stdoutFile, "a");
             // change output stream
             // change output stream
             static::$_outputStream = null;
             static::$_outputStream = null;
             static::outputStream($STDOUT);
             static::outputStream($STDOUT);
             \restore_error_handler();
             \restore_error_handler();
-        } else {
-            throw new Exception('can not open stdoutFile ' . static::$stdoutFile);
+            return;
         }
         }
+
+        throw new Exception('Can not open stdoutFile ' . static::$stdoutFile);
     }
     }
 
 
     /**
     /**
@@ -1617,7 +1618,7 @@ class Worker
             \pcntl_signal_dispatch();
             \pcntl_signal_dispatch();
             // Suspends execution of the current process until a child has exited, or until a signal is delivered
             // Suspends execution of the current process until a child has exited, or until a signal is delivered
             $status = 0;
             $status = 0;
-            $pid    = \pcntl_wait($status, WUNTRACED);
+            $pid    = \pcntl_wait($status, \WUNTRACED);
             // Calls signal handlers for pending signals again.
             // Calls signal handlers for pending signals again.
             \pcntl_signal_dispatch();
             \pcntl_signal_dispatch();
             // If a child has already exited.
             // If a child has already exited.
@@ -1728,9 +1729,9 @@ class Worker
             }
             }
 
 
             if (static::$_gracefulStop) {
             if (static::$_gracefulStop) {
-                $sig = SIGQUIT;
+                $sig = \SIGQUIT;
             } else {
             } else {
-                $sig = SIGUSR1;
+                $sig = \SIGUSR1;
             }
             }
 
 
             // Send reload signal to all child processes.
             // Send reload signal to all child processes.
@@ -1765,7 +1766,7 @@ class Worker
             \posix_kill($one_worker_pid, $sig);
             \posix_kill($one_worker_pid, $sig);
             // If the process does not exit after static::KILL_WORKER_TIMER_TIME seconds try to kill it.
             // If the process does not exit after static::KILL_WORKER_TIMER_TIME seconds try to kill it.
             if(!static::$_gracefulStop){
             if(!static::$_gracefulStop){
-                Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($one_worker_pid, SIGKILL), false);
+                Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($one_worker_pid, \SIGKILL), false);
             }
             }
         } // For child processes.
         } // For child processes.
         else {
         else {
@@ -1804,14 +1805,14 @@ class Worker
             $worker_pid_array = static::getAllWorkerPids();
             $worker_pid_array = static::getAllWorkerPids();
             // Send stop signal to all child processes.
             // Send stop signal to all child processes.
             if (static::$_gracefulStop) {
             if (static::$_gracefulStop) {
-                $sig = SIGTERM;
+                $sig = \SIGTERM;
             } else {
             } else {
-                $sig = SIGINT;
+                $sig = \SIGINT;
             }
             }
             foreach ($worker_pid_array as $worker_pid) {
             foreach ($worker_pid_array as $worker_pid) {
                 \posix_kill($worker_pid, $sig);
                 \posix_kill($worker_pid, $sig);
                 if(!static::$_gracefulStop){
                 if(!static::$_gracefulStop){
-                    Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($worker_pid, SIGKILL), false);
+                    Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($worker_pid, \SIGKILL), false);
                 }
                 }
             }
             }
             Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
             Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
@@ -1890,49 +1891,49 @@ class Worker
                 }
                 }
             }
             }
 
 
-            \file_put_contents(static::$_statisticsFile, \json_encode($all_worker_info)."\n", FILE_APPEND);
-            $loadavg = \function_exists('sys_getloadavg') ? \array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
+            \file_put_contents(static::$_statisticsFile, \json_encode($all_worker_info)."\n", \FILE_APPEND);
+            $loadavg = \function_exists('sys_getloadavg') ? \array_map('round', \sys_getloadavg(), array(2)) : array('-', '-', '-');
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
-                "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
+                "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
-                'Workerman version:' . static::VERSION . "          PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
+                'Workerman version:' . static::VERSION . "          PHP version:" . \PHP_VERSION . "\n", \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile, 'start time:' . \date('Y-m-d H:i:s',
             \file_put_contents(static::$_statisticsFile, 'start time:' . \date('Y-m-d H:i:s',
                     static::$_globalStatistics['start_timestamp']) . '   run ' . \floor((\time() - static::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . \floor(((\time() - static::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours   \n",
                     static::$_globalStatistics['start_timestamp']) . '   run ' . \floor((\time() - static::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . \floor(((\time() - static::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours   \n",
                 FILE_APPEND);
                 FILE_APPEND);
             $load_str = 'load average: ' . \implode(", ", $loadavg);
             $load_str = 'load average: ' . \implode(", ", $loadavg);
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
-                \str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", FILE_APPEND);
+                \str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
                 \count(static::$_pidMap) . ' workers       ' . \count(static::getAllWorkerPids()) . " processes\n",
                 \count(static::$_pidMap) . ' workers       ' . \count(static::getAllWorkerPids()) . " processes\n",
-                FILE_APPEND);
+                \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
-                \str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status      exit_count\n", FILE_APPEND);
+                \str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status      exit_count\n", \FILE_APPEND);
             foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
             foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
                 $worker = static::$_workers[$worker_id];
                 $worker = static::$_workers[$worker_id];
                 if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
                 if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
                     foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
                     foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
                         \file_put_contents(static::$_statisticsFile,
                         \file_put_contents(static::$_statisticsFile,
                             \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad($worker_exit_status,
                             \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad($worker_exit_status,
-                                16) . " $worker_exit_count\n", FILE_APPEND);
+                                16) . " $worker_exit_count\n", \FILE_APPEND);
                     }
                     }
                 } else {
                 } else {
                     \file_put_contents(static::$_statisticsFile,
                     \file_put_contents(static::$_statisticsFile,
                         \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad(0, 16) . " 0\n",
                         \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad(0, 16) . " 0\n",
-                        FILE_APPEND);
+                        \FILE_APPEND);
                 }
                 }
             }
             }
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
                 "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
                 "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
-                FILE_APPEND);
+                \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
             \file_put_contents(static::$_statisticsFile,
                 "pid\tmemory  " . \str_pad('listening', static::$_maxSocketNameLength) . " " . \str_pad('worker_name',
                 "pid\tmemory  " . \str_pad('listening', static::$_maxSocketNameLength) . " " . \str_pad('worker_name',
                     static::$_maxWorkerNameLength) . " connections " . \str_pad('send_fail', 9) . " "
                     static::$_maxWorkerNameLength) . " connections " . \str_pad('send_fail', 9) . " "
-                . \str_pad('timers', 8) . \str_pad('total_request', 13) ." qps    status\n", FILE_APPEND);
+                . \str_pad('timers', 8) . \str_pad('total_request', 13) ." qps    status\n", \FILE_APPEND);
 
 
             \chmod(static::$_statisticsFile, 0722);
             \chmod(static::$_statisticsFile, 0722);
 
 
             foreach (static::getAllWorkerPids() as $worker_pid) {
             foreach (static::getAllWorkerPids() as $worker_pid) {
-                \posix_kill($worker_pid, SIGUSR2);
+                \posix_kill($worker_pid, \SIGUSR2);
             }
             }
             return;
             return;
         }
         }
@@ -1943,13 +1944,13 @@ class Worker
         $worker            = current(static::$_workers);
         $worker            = current(static::$_workers);
         $worker_status_str = \posix_getpid() . "\t" . \str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
         $worker_status_str = \posix_getpid() . "\t" . \str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
             . " " . \str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
             . " " . \str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
-            . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
+            . \str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
             . " ";
             . " ";
         $worker_status_str .= \str_pad(ConnectionInterface::$statistics['connection_count'], 11)
         $worker_status_str .= \str_pad(ConnectionInterface::$statistics['connection_count'], 11)
             . " " .  \str_pad(ConnectionInterface::$statistics['send_fail'], 9)
             . " " .  \str_pad(ConnectionInterface::$statistics['send_fail'], 9)
             . " " . \str_pad(static::$globalEvent->getTimerCount(), 7)
             . " " . \str_pad(static::$globalEvent->getTimerCount(), 7)
             . " " . \str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
             . " " . \str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
-        \file_put_contents(static::$_statisticsFile, $worker_status_str, FILE_APPEND);
+        \file_put_contents(static::$_statisticsFile, $worker_status_str, \FILE_APPEND);
     }
     }
 
 
     /**
     /**
@@ -1961,11 +1962,11 @@ class Worker
     {
     {
         // For master process.
         // For master process.
         if (static::$_masterPid === \posix_getpid()) {
         if (static::$_masterPid === \posix_getpid()) {
-            \file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
-            \file_put_contents(static::$_statisticsFile, "PID      Worker          CID       Trans   Protocol        ipv4   ipv6   Recv-Q       Send-Q       Bytes-R      Bytes-W       Status         Local Address          Foreign Address\n", FILE_APPEND);
+            \file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", \FILE_APPEND);
+            \file_put_contents(static::$_statisticsFile, "PID      Worker          CID       Trans   Protocol        ipv4   ipv6   Recv-Q       Send-Q       Bytes-R      Bytes-W       Status         Local Address          Foreign Address\n", \FILE_APPEND);
             \chmod(static::$_statisticsFile, 0722);
             \chmod(static::$_statisticsFile, 0722);
             foreach (static::getAllWorkerPids() as $worker_pid) {
             foreach (static::getAllWorkerPids() as $worker_pid) {
-                \posix_kill($worker_pid, SIGIO);
+                \posix_kill($worker_pid, \SIGIO);
             }
             }
             return;
             return;
         }
         }
@@ -2026,7 +2027,7 @@ class Worker
                 . \str_pad($state, 14) . ' ' . \str_pad($local_address, 22) . ' ' . \str_pad($remote_address, 22) ."\n";
                 . \str_pad($state, 14) . ' ' . \str_pad($local_address, 22) . ' ' . \str_pad($remote_address, 22) ."\n";
         }
         }
         if ($str) {
         if ($str) {
-            \file_put_contents(static::$_statisticsFile, $str, FILE_APPEND);
+            \file_put_contents(static::$_statisticsFile, $str, \FILE_APPEND);
         }
         }
     }
     }
 
 
@@ -2040,11 +2041,11 @@ class Worker
         if (static::STATUS_SHUTDOWN !== static::$_status) {
         if (static::STATUS_SHUTDOWN !== static::$_status) {
             $error_msg = static::$_OS === OS_TYPE_LINUX ? 'Worker['. \posix_getpid() .'] process terminated' : 'Worker process terminated';
             $error_msg = static::$_OS === OS_TYPE_LINUX ? 'Worker['. \posix_getpid() .'] process terminated' : 'Worker process terminated';
             $errors    = error_get_last();
             $errors    = error_get_last();
-            if ($errors && ($errors['type'] === E_ERROR ||
-                    $errors['type'] === E_PARSE ||
-                    $errors['type'] === E_CORE_ERROR ||
-                    $errors['type'] === E_COMPILE_ERROR ||
-                    $errors['type'] === E_RECOVERABLE_ERROR)
+            if ($errors && ($errors['type'] === \E_ERROR ||
+                    $errors['type'] === \E_PARSE ||
+                    $errors['type'] === \E_CORE_ERROR ||
+                    $errors['type'] === \E_COMPILE_ERROR ||
+                    $errors['type'] === \E_RECOVERABLE_ERROR)
             ) {
             ) {
                 $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
                 $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
             }
             }
@@ -2080,7 +2081,7 @@ class Worker
             static::safeEcho($msg);
             static::safeEcho($msg);
         }
         }
         \file_put_contents((string)static::$logFile, \date('Y-m-d H:i:s') . ' ' . 'pid:'
         \file_put_contents((string)static::$logFile, \date('Y-m-d H:i:s') . ' ' . 'pid:'
-            . (static::$_OS === OS_TYPE_LINUX ? \posix_getpid() : 1) . ' ' . $msg, FILE_APPEND | LOCK_EX);
+            . (static::$_OS === OS_TYPE_LINUX ? \posix_getpid() : 1) . ' ' . $msg, \FILE_APPEND | \LOCK_EX);
     }
     }
 
 
     /**
     /**
@@ -2120,7 +2121,7 @@ class Worker
     private static function outputStream($stream = null)
     private static function outputStream($stream = null)
     {
     {
         if (!$stream) {
         if (!$stream) {
-            $stream = static::$_outputStream ? static::$_outputStream : STDOUT;
+            $stream = static::$_outputStream ? static::$_outputStream : \STDOUT;
         }
         }
         if (!$stream || !\is_resource($stream) || 'stream' !== \get_resource_type($stream)) {
         if (!$stream || !\is_resource($stream) || 'stream' !== \get_resource_type($stream)) {
             return false;
             return false;
@@ -2152,14 +2153,14 @@ class Worker
         static::$_pidMap[$this->workerId]  = array();
         static::$_pidMap[$this->workerId]  = array();
 
 
         // Get autoload root path.
         // Get autoload root path.
-        $backtrace                = \debug_backtrace();
+        $backtrace               = \debug_backtrace();
         $this->_autoloadRootPath = \dirname($backtrace[0]['file']);
         $this->_autoloadRootPath = \dirname($backtrace[0]['file']);
         Autoloader::setRootPath($this->_autoloadRootPath);
         Autoloader::setRootPath($this->_autoloadRootPath);
 
 
         // Turn reusePort on.
         // Turn reusePort on.
         if (static::$_OS === OS_TYPE_LINUX  // if linux
         if (static::$_OS === OS_TYPE_LINUX  // if linux
-                            && version_compare(PHP_VERSION,'7.0.0', 'ge') // if php >= 7.0.0
-                            && strtolower(php_uname('s')) !== 'darwin') { // if not Mac OS
+                            && \version_compare(\PHP_VERSION,'7.0.0', 'ge') // if php >= 7.0.0
+                            && \strtolower(\php_uname('s')) !== 'darwin') { // if not Mac OS
 
 
             $this->reusePort = true;
             $this->reusePort = true;
         }
         }
@@ -2195,7 +2196,7 @@ class Worker
             $local_socket = !empty($this->_localSocket) ? $this->_localSocket : $this->parseSocketAddress();
             $local_socket = !empty($this->_localSocket) ? $this->_localSocket : $this->parseSocketAddress();
 
 
             // Flag.
             // Flag.
-            $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
+            $flags = $this->transport === 'udp' ? \STREAM_SERVER_BIND : \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN;
             $errno = 0;
             $errno = 0;
             $errmsg = '';
             $errmsg = '';
             // SO_REUSEPORT.
             // SO_REUSEPORT.
@@ -2214,10 +2215,10 @@ class Worker
             } elseif ($this->transport === 'unix') {
             } elseif ($this->transport === 'unix') {
                 $socket_file = \substr($local_socket, 7);
                 $socket_file = \substr($local_socket, 7);
                 if ($this->user) {
                 if ($this->user) {
-                    chown($socket_file, $this->user);
+                    \chown($socket_file, $this->user);
                 }
                 }
                 if ($this->group) {
                 if ($this->group) {
-                    chgrp($socket_file, $this->group);
+                    \chgrp($socket_file, $this->group);
                 }
                 }
             }
             }
 
 
@@ -2225,8 +2226,8 @@ class Worker
             if (\function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
             if (\function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
                 \set_error_handler(function(){});
                 \set_error_handler(function(){});
                 $socket = \socket_import_stream($this->_mainSocket);
                 $socket = \socket_import_stream($this->_mainSocket);
-                \socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
-                \socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
+                \socket_set_option($socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
+                \socket_set_option($socket, \SOL_TCP, \TCP_NODELAY, 1);
                 \restore_error_handler();
                 \restore_error_handler();
             }
             }
 
 
@@ -2275,7 +2276,7 @@ class Worker
             }
             }
 
 
             if (!isset(static::$_builtinTransports[$this->transport])) {
             if (!isset(static::$_builtinTransports[$this->transport])) {
-                throw new \Exception('Bad worker->transport ' . \var_export($this->transport, true));
+                throw new Exception('Bad worker->transport ' . \var_export($this->transport, true));
             }
             }
         } else {
         } else {
             $this->transport = $scheme;
             $this->transport = $scheme;
@@ -2322,7 +2323,7 @@ class Worker
      */
      */
     public function getSocketName()
     public function getSocketName()
     {
     {
-        return $this->_socketName ? lcfirst($this->_socketName) : 'none';
+        return $this->_socketName ? \lcfirst($this->_socketName) : 'none';
     }
     }
 
 
     /**
     /**
@@ -2423,7 +2424,7 @@ class Worker
     {
     {
         // Accept a connection on server socket.
         // Accept a connection on server socket.
         \set_error_handler(function(){});
         \set_error_handler(function(){});
-        $new_socket = stream_socket_accept($socket, 0, $remote_address);
+        $new_socket = \stream_socket_accept($socket, 0, $remote_address);
         \restore_error_handler();
         \restore_error_handler();
 
 
         // Thundering herd.
         // Thundering herd.