Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: code improvements without affecting logic, part 4. #300

Merged
merged 2 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 17 additions & 17 deletions src/Engine/Engine.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ class Engine extends Emitter
'Bad request'
];

const ERROR_UNKNOWN_TRANSPORT = 0;
private const ERROR_UNKNOWN_TRANSPORT = 0;

const ERROR_UNKNOWN_SID = 1;
private const ERROR_UNKNOWN_SID = 1;

const ERROR_BAD_HANDSHAKE_METHOD = 2;
private const ERROR_BAD_HANDSHAKE_METHOD = 2;

const ERROR_BAD_REQUEST = 3;
private const ERROR_BAD_REQUEST = 3;

public function __construct($opts = [])
{
Expand All @@ -48,6 +48,7 @@ public function __construct($opts = [])
'allowUpgrades',
'allowRequest'
];

foreach ($ops_map as $key) {
if (isset($opts[$key])) {
$this->$key = $opts[$key];
Expand All @@ -61,7 +62,7 @@ public function __destruct()
Debug::debug('Engine __destruct');
}

public function handleRequest($req, $res)
public function handleRequest(object $req, object $res)
{
$this->prepare($req);
$req->res = $res;
Expand All @@ -71,7 +72,7 @@ public function handleRequest($req, $res)
/**
* @throws Exception
*/
public function dealRequest($err, $success, $req)
public function dealRequest($err, bool $success, object $req)
{
if (! $success) {
self::sendErrorMessage($req, $req->res, $err);
Expand All @@ -85,7 +86,7 @@ public function dealRequest($err, $success, $req)
}
}

protected function sendErrorMessage($req, $res, $code)
protected function sendErrorMessage(object $req, object $res, string $code): void
{
$headers = ['Content-Type' => 'application/json'];
if (isset($req->headers['origin'])) {
Expand All @@ -106,7 +107,7 @@ protected function sendErrorMessage($req, $res, $code)
);
}

protected function verify($req, $res, $upgrade, $fn)
protected function verify(object $req, object $res, bool $upgrade, callable $fn)
{
if (! isset($req->_query['transport']) || ! isset(self::$allowTransports[$req->_query['transport']])) {
return call_user_func($fn, self::ERROR_UNKNOWN_TRANSPORT, false, $req, $res);
Expand All @@ -129,7 +130,7 @@ protected function verify($req, $res, $upgrade, $fn)
call_user_func($fn, null, true, $req, $res);
}

public function checkRequest($req, $res, $fn)
public function checkRequest(object $req, object $res, callable $fn)
{
if ($this->origins === "*:*" || empty($this->origins)) {
return call_user_func($fn, null, true, $req, $res);
Expand Down Expand Up @@ -158,15 +159,14 @@ public function checkRequest($req, $res, $fn)
$allow_origin === $parts['scheme'] . '://' . $parts['host'] . ':*' ||
$allow_origin === '*:' . $parts['port'];
if ($ok) {
// 只需要有一个白名单通过,则都通过
return call_user_func($fn, null, true, $req, $res);
}
}
}
call_user_func($fn, null, false, $req, $res);
}

protected function prepare($req)
protected function prepare(object $req)
{
if (! isset($req->_query)) {
$info = parse_url($req->url);
Expand All @@ -179,7 +179,7 @@ protected function prepare($req)
/**
* @throws Exception
*/
public function handshake($transport, $req)
public function handshake(string $transport, object $req)
{
$id = bin2hex(pack('d', microtime(true)) . pack('N', function_exists('random_int') ? random_int(1, 100000000) : rand(1, 100000000)));
if ($transport == 'websocket') {
Expand All @@ -203,18 +203,18 @@ public function handshake($transport, $req)
$this->emit('connection', $socket);
}

public function onSocketClose($id)
public function onSocketClose($id): void
{
unset($this->clients[$id]);
}

public function attach($worker)
public function attach($worker): void
{
$this->server = $worker;
$worker->onConnect = [$this, 'onConnect'];
}

public function onConnect($connection)
public function onConnect(object $connection): void
{
$connection->onRequest = [$this, 'handleRequest'];
$connection->onWebSocketConnect = [$this, 'onWebSocketConnect'];
Expand All @@ -237,7 +237,7 @@ public function onConnect($connection)
};
}

public function onWebSocketConnect($connection, $req, $res)
public function onWebSocketConnect($connection, object $req, object $res): void
{
$this->prepare($req);
$this->verify($req, $res, true, [$this, 'dealWebSocketConnect']);
Expand All @@ -246,7 +246,7 @@ public function onWebSocketConnect($connection, $req, $res)
/**
* @throws Exception
*/
public function dealWebSocketConnect($err, $success, $req, $res)
public function dealWebSocketConnect($err, bool $success, object $req, object $res): void
{
if (! $success) {
self::sendErrorMessage($req, $res, $err);
Expand Down
39 changes: 10 additions & 29 deletions src/Engine/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,32 +43,15 @@ public static function encodePacket($packet): string
return self::$packets[$packet['type']] . $data;
}


/**
* Encodes a packet with binary data in a base64 string
*
* @param {Object} packet, has `type` and `data`
* @return string {String} base64 encoded message
*/
public static function encodeBase64Packet($packet): string
{
return 'b' . self::$packets[$packet['type']] . base64_encode($packet['data']);
}

/**
* Decodes a packet. Data also available as an ArrayBuffer if requested.
*
* @param $data
* @param null $binaryType
* @param bool $utf8decode
* @return array|string[] {Object} with `type` and `data` (if any)
* @api private
*/
public static function decodePacket($data, $binaryType = null, $utf8decode = true)
public static function decodePacket(string $data): array
{
// String data todo check if (typeof data == 'string' || data === undefined)
if ($data[0] === 'b') {
return self::decodeBase64Packet(substr($data, 1), $binaryType);
return self::decodeBase64Packet(substr($data, 1));
}

$type = $data[0];
Expand All @@ -87,13 +70,12 @@ public static function decodePacket($data, $binaryType = null, $utf8decode = tru
* Decodes a packet encoded in a base64 string.
*
* @param $msg
* @param $binaryType
* @return array {Object} with `type` and `data` (if any)
*/
public static function decodeBase64Packet($msg, $binaryType)
public static function decodeBase64Packet($msg): array
{
$type = self::$packetsList[$msg[0]];
$data = base64_decode(substr($data, 1));
$data = base64_decode(substr($msg, 1));
return ['type' => $type, 'data' => $data];
}

Expand Down Expand Up @@ -124,12 +106,12 @@ public static function encodePayload($packets, $supportsBinary = null): string

$results = '';
foreach ($packets as $msg) {
$results .= self::encodeOne($msg, $supportsBinary);
$results .= self::encodeOne($msg);
}
return $results;
}

public static function encodeOne($packet, $supportsBinary = null, $result = null): string
public static function encodeOne($packet): string
{
$message = self::encodePacket($packet);
return strlen($message) . ':' . $message;
Expand Down Expand Up @@ -165,10 +147,10 @@ public static function decodePayload($data, $binaryType = null)
return self::$err;
}

$msg = substr($data, $i + 1/*, $n*/);
$msg = substr($data, $i + 1);

if (isset($msg[0])) {
$packet = self::decodePacket($msg, $binaryType);
$packet = self::decodePacket($msg);

if (self::$err['type'] == $packet['type'] && self::$err['data'] == $packet['data']) {
// parser error in individual packet - ignoring payload
Expand Down Expand Up @@ -215,7 +197,6 @@ public static function encodePayloadAsBinary($packets): string

public static function encodeOneAsBinary($p): string
{
// todo is string or arraybuf
$packet = self::encodePacket($p);
$encodingLength = '' . strlen($packet);
$sizeBuffer = chr(0);
Expand Down Expand Up @@ -257,15 +238,15 @@ public static function decodePayloadAsBinary($data, $binaryType = null): array
}
$bufferTail = substr($bufferTail, strlen($strLen) + 1);

$msgLength = intval($strLen, 10);
$msgLength = intval($strLen);

$msg = substr($bufferTail, 1, $msgLength + 1);
$buffers[] = $msg;
$bufferTail = substr($bufferTail, $msgLength + 1);
}
$packets = [];
foreach ($buffers as $i => $buffer) {
$packets[] = self::decodePacket($buffer, $binaryType);
$packets[] = self::decodePacket($buffer);
}
return $packets;
}
Expand Down