Skip to content
This repository was archived by the owner on Mar 24, 2025. It is now read-only.

Commit 0159eba

Browse files
committed
add isUserIdOnline and logout apis for websocket
1 parent 9bebcc9 commit 0159eba

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

src/Websocket/Authenticatable.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ public function loginUsingId($userId)
2525
return $this->join(static::USER_PREFIX . $userId);
2626
}
2727

28+
/**
29+
* Logout with current sender's fd.
30+
*/
31+
public function logout()
32+
{
33+
if (is_null($userId = $this->getUserId())) {
34+
return;
35+
}
36+
37+
return $this->leave(static::USER_PREFIX . $userId);
38+
}
39+
2840
/**
2941
* Set multiple recepients' fds by users.
3042
*/
@@ -75,6 +87,14 @@ public function getUserId()
7587
return $this->userId;
7688
}
7789

90+
/**
91+
* Check if a user is online by given userId.
92+
*/
93+
public function isUserIdOnline($userId)
94+
{
95+
return ! empty($this->room->getClients(static::USER_PREFIX . $userId));
96+
}
97+
7898
/**
7999
* Check if user object implements AuthenticatableContract.
80100
*/

src/Websocket/Websocket.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ protected function getFds()
296296

297297
foreach ($rooms as $room) {
298298
$clients = $this->room->getClients($room);
299-
// rollback fd with wrong type back to fds array
299+
// fallback fd with wrong type back to fds array
300300
if (empty($clients) && is_numeric($room)) {
301301
$fds[] = $room;
302302
} else {

tests/Websocket/WebsocketTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,33 @@ public function testGetUserId()
205205
$this->assertEquals($sender, $websocket->getUserId());
206206
}
207207

208+
public function testLogout()
209+
{
210+
$room = m::mock(RoomContract::class);
211+
$room->shouldReceive('getRooms')
212+
->with($sender = 1)
213+
->once()
214+
->andReturn(['uid_1']);
215+
$room->shouldReceive('delete')
216+
->with($sender, $name = ['uid_1'])
217+
->once();
218+
219+
$websocket = $this->getWebsocket($room)->setSender($sender);
220+
$websocket->logout();
221+
}
222+
223+
public function testIsUserIdOnline()
224+
{
225+
$room = m::mock(RoomContract::class);
226+
$room->shouldReceive('getClients')
227+
->with('uid_1')
228+
->once()
229+
->andReturn([1]);
230+
231+
$websocket = $this->getWebsocket($room);
232+
$this->assertTrue($websocket->isUserIdOnline(1));
233+
}
234+
208235
public function testReset()
209236
{
210237
$websocket = $this->getWebsocket();

0 commit comments

Comments
 (0)