Skip to content

Commit

Permalink
refactor: code improvements without affecting logic, part 4.
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcos Marcolin committed Oct 11, 2023
1 parent 48a5baa commit 5bcac8a
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 79 deletions.
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
40 changes: 18 additions & 22 deletions src/Engine/Transports/Polling.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ class Polling extends Transport
public $chunks = '';
public $shouldClose = null;
public $writable = false;
public $supportsBinary = null;
public $dataRes = null;
public $dataReq = null;

public function onRequest($req)
{
Expand All @@ -26,11 +29,9 @@ public function onRequest($req)
}
}

public function onPollRequest($req, $res)
public function onPollRequest(object $req, object $res): void
{
if ($this->req) {
echo('request overlap');
// assert: this.res, '.req and .res should be (un)set together'
$this->onError('overlap from client');
$res->writeHead(500);
return;
Expand All @@ -45,32 +46,29 @@ public function onPollRequest($req, $res)
$this->writable = true;
$this->emit('drain');

// if we're still writable but had a pending close, trigger an empty send
if ($this->writable && $this->shouldClose) {
echo('triggering empty send to append close packet');
$this->send([['type' => 'noop']]);
}
}

public function pollRequestOnClose()
public function pollRequestOnClose(): void
{
$this->onError('poll connection closed prematurely');
$this->pollRequestClean();
}

public function pollRequestClean()
public function pollRequestClean(): void
{
if (isset($this->req)) {
$this->req->res = null;
$this->req->onClose = $this->req->cleanup = null;
$this->req = $this->res = null;
$this->req = null;
$this->res = null;
}
}

public function onDataRequest($req, $res)
public function onDataRequest($req, $res): void
{
if (isset($this->dataReq)) {
// assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
$this->onError('data request overlap from client');
$res->writeHead(500);
return;
Expand All @@ -83,26 +81,25 @@ public function onDataRequest($req, $res)
$req->onEnd = [$this, 'dataRequestOnEnd'];
}

public function dataRequestCleanup()
public function dataRequestCleanup(): void
{
$this->chunks = '';
$this->dataReq->res = null;
$this->dataReq->onClose = $this->dataReq->onData = $this->dataReq->onEnd = null;
$this->dataReq = $this->dataRes = null;
$this->dataReq = null;
$this->dataRes = null;
}

public function dataRequestOnClose()
public function dataRequestOnClose(): void
{
$this->dataRequestCleanup();
$this->onError('data request connection closed prematurely');
}

public function dataRequestOnData($req, $data)
public function dataRequestOnData($req, $data): void
{
$this->chunks .= $data;
}

public function dataRequestOnEnd()
public function dataRequestOnEnd(): void
{
$this->onData($this->chunks);

Expand Down Expand Up @@ -137,13 +134,12 @@ public function onData($data)
public function onClose()
{
if ($this->writable) {
// close pending poll request
$this->send([['type' => 'noop']]);
}
parent::onClose();
}

public function send($packets)
public function send($packets): void
{
$this->writable = false;
if ($this->shouldClose) {
Expand All @@ -156,15 +152,15 @@ public function send($packets)
$this->write($data);
}

public function write($data)
public function write($data): void
{
$this->doWrite($data);
if (! empty($this->req->cleanup)) {
call_user_func($this->req->cleanup);
}
}

public function doClose($fn)
public function doClose(callable $fn): void
{
if (! empty($this->dataReq)) {
$this->dataReq->destroy();
Expand Down
Loading

0 comments on commit 5bcac8a

Please sign in to comment.