diff --git a/src/Websocket/Handler.php b/src/Websocket/Handler.php index 4a6ddb8..366adeb 100644 --- a/src/Websocket/Handler.php +++ b/src/Websocket/Handler.php @@ -504,12 +504,21 @@ class Handler implements MessageComponentInterface return false; } - $connection->send(json_encode([ + $response = [ 'event' => $event . ':response', 'data' => [ 'message' => 'Success', ], - ])); + ]; + + // Name the channel, as the :error reply to a refused subscribe does, + // so a client with several subscribes in flight can match the reply. + $channelName = $message['channel'] ?? ($message['data']['channel'] ?? null); + if (is_string($channelName) && $channelName !== '') { + $response['channel'] = $channelName; + } + + $connection->send(json_encode($response)); return true; } diff --git a/tests/HandlerLifecycleTest.php b/tests/HandlerLifecycleTest.php index 2159676..f3ebe8c 100644 --- a/tests/HandlerLifecycleTest.php +++ b/tests/HandlerLifecycleTest.php @@ -695,6 +695,33 @@ class HandlerLifecycleTest extends TestCase $response = collect($connection->sentData)->firstWhere('event', 'websocket.subscribe:response'); $this->assertNotNull($response); $this->assertEquals('Success', $response['data']['message']); + $this->assertSame('websocket', $response['channel']); + } + + public function test_responses_to_concurrent_subscribes_name_their_channel() + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['channel' => 'websocket'], + ])); + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['auth' => 'TestKey:invalid-signature', 'channel' => 'private-test'], + ])); + + $replies = collect($connection->sentData) + ->filter(fn ($frame) => str_starts_with($frame['event'] ?? '', 'websocket.subscribe:')) + ->map(fn ($frame) => [$frame['event'], $frame['channel'] ?? null]) + ->values() + ->all(); + + $this->assertSame([ + ['websocket.subscribe:response', 'websocket'], + ['websocket.subscribe:error', 'private-test'], + ], $replies); } public function test_unsubscribe_gets_response_suffix() @@ -709,6 +736,7 @@ class HandlerLifecycleTest extends TestCase $response = collect($connection->sentData)->firstWhere('event', 'websocket.unsubscribe:response'); $this->assertNotNull($response); + $this->assertSame('websocket', $response['channel']); } // =========================================================================