From d9377392c3ea2d1202d5882a1b7e40edd6b267d5 Mon Sep 17 00:00:00 2001 From: pandaLIU <26201936+PandaLIU-1111@users.noreply.github.com> Date: Sat, 13 Jan 2024 08:44:06 +0800 Subject: [PATCH] Optimized code for socketio decode. (#6462) --- src/socketio-server/src/Parser/Decoder.php | 47 +++++++------------ .../tests/Cases/DecoderTest.php | 9 ++++ 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/src/socketio-server/src/Parser/Decoder.php b/src/socketio-server/src/Parser/Decoder.php index 41204c742..a1567b5c5 100644 --- a/src/socketio-server/src/Parser/Decoder.php +++ b/src/socketio-server/src/Parser/Decoder.php @@ -46,41 +46,30 @@ class Decoder if ($currentIndex + 1 === $payloadLength) { goto _out; } + if ($payload[$currentIndex + 1] === '/') { - $start = $currentIndex + 1; - while (++$currentIndex) { - if ($currentIndex === $payloadLength) { - break; - } - $char = $payload[$currentIndex]; - if ($char === ',') { - break; - } + $nspStart = $currentIndex + 1; + $nspEnd = strpos($payload, ','); + $queryStart = strpos($payload, '?'); + + $currentIndex = $nspEnd !== false ? $nspEnd : $payloadLength; + + if ($queryStart !== false) { + $queryLength = $nspEnd === false ? $currentIndex - $queryStart : $currentIndex - $queryStart - 1; + $queryStr = substr($payload, $queryStart + 1, $queryLength); + + $nsp = substr($payload, $nspStart, $queryStart - $nspStart); + parse_str($queryStr, $query); + } else { + $nsp = substr($payload, $nspStart, $currentIndex - $nspStart); } - $nspStart = $start; - $nspEnd = $currentIndex; - $queryStart = $nspStart; - // look up query in namespace (e.g. "1/ws?foo=bar&baz=1,") - while (++$queryStart) { - if ($queryStart === $currentIndex) { - break; - } - $char = $payload[$queryStart]; - if ($char === '?') { - $queryLength = $nspEnd - $queryStart; - $queryStr = substr($payload, $queryStart + 1, $queryLength - 1); - parse_str($queryStr, $query); - $nspEnd = $queryStart; - break; - } - } - $nsp = substr($payload, $nspStart, $nspEnd - $nspStart); } - // look up id - if ($currentIndex === $payloadLength) { + if ($currentIndex >= $payloadLength) { goto _out; } + + // Parser packet id $start = $currentIndex + 1; while (++$currentIndex) { if ($currentIndex === $payloadLength) { diff --git a/src/socketio-server/tests/Cases/DecoderTest.php b/src/socketio-server/tests/Cases/DecoderTest.php index 3b9424970..11bd9a9f0 100644 --- a/src/socketio-server/tests/Cases/DecoderTest.php +++ b/src/socketio-server/tests/Cases/DecoderTest.php @@ -88,6 +88,15 @@ class DecoderTest extends AbstractTestCase ], $result->query); $this->assertEquals(['event' => 'JOIN'], $result->data); + $result = $decoder->decode('42/1?foo=xxx&bar=yyy'); + $this->assertEquals(2, $result->type); + $this->assertEquals('/1', $result->nsp); + $this->assertEquals('', $result->id); + $this->assertEquals([ + 'foo' => 'xxx', + 'bar' => 'yyy', + ], $result->query); + try { $decoder->decode('42/1?2["event","hellohyperf"]'); $this->assertTrue(false);