119 lines
1.7 KiB
PHP
119 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Coroutine\Server;
|
|
|
|
class Transport
|
|
{
|
|
|
|
/**
|
|
* @var array<Struct>
|
|
*/
|
|
private array $clients = [];
|
|
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @param Struct $data
|
|
* @return void
|
|
*/
|
|
public function add(int $fd, Struct $data): void
|
|
{
|
|
if (isset($this->clients[$fd])) {
|
|
$this->clients[$fd]->ws->close();
|
|
}
|
|
$this->clients[$fd] = $data;
|
|
}
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @param mixed $data
|
|
* @return void
|
|
*/
|
|
public function send(int $fd, mixed $data): void
|
|
{
|
|
if (isset($this->clients[$fd])) {
|
|
$this->clients[$fd]->ws->push($data);
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @return void
|
|
*/
|
|
public function close(int $fd): void
|
|
{
|
|
if (isset($this->clients[$fd])) {
|
|
$this->clients[$fd]->ws->close();
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @return void
|
|
*/
|
|
public function remove(int $fd): void
|
|
{
|
|
if ($this->has($fd)) {
|
|
$this->clients[$fd]?->ws->close();
|
|
}
|
|
unset($this->clients[$fd]);
|
|
}
|
|
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @return Struct|null
|
|
*/
|
|
public function getClientId(int $fd): ?Struct
|
|
{
|
|
return array_find($this->clients, fn($client) => $client->fd == $fd);
|
|
}
|
|
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @return Struct|null
|
|
*/
|
|
public function getUserId(int $fd): ?Struct
|
|
{
|
|
return $this->clients[$fd] ?? null;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param int $fd
|
|
* @return bool
|
|
*/
|
|
public function has(int $fd): bool
|
|
{
|
|
return isset($this->clients[$fd]);
|
|
}
|
|
|
|
|
|
/**
|
|
* @return array
|
|
*/
|
|
public function getLists(): array
|
|
{
|
|
$array = [];
|
|
foreach ($this->clients as $fd => $client) {
|
|
$array[] = [
|
|
'userId' => $fd,
|
|
'nickname' => $client->user->getNickname(),
|
|
];
|
|
}
|
|
return $array;
|
|
}
|
|
|
|
|
|
/**
|
|
* @return int
|
|
*/
|
|
public function size(): int
|
|
{
|
|
return count($this->clients);
|
|
}
|
|
}
|