<?phpnamespace Tests\Cloud;use JumPHP\Kernel\GameConfig;use JumPHP\Net\NetSession;use PhpWasmNetwork\Connection;use PhpWasmNetwork\Event;/** * The relay of php-wasm-network (with room-id.patch) in memory: private rooms by a long id, peers, messages to one peer * or to all. Everything that went through it is kept ($traffic): the tests check it is only ciphertext. */final class FakeRelay{ /** @var array<string, array<int, FakeRelayConnection>> */ public array $rooms = []; public int $nextPeer = 0; /** @var list<string> every message relayed */ public array $traffic = []; /** A NetSession on this relay (what Cloud takes as its factory). */ public function session(): NetSession { $net = new NetSession(new GameConfig(['id' => 'winzik'])); $net->attach(new FakeRelayConnection($this)); return $net; }}final class FakeRelayConnection implements Connection{ /** @var list<Event> */ public array $events = []; public int $peer = -1; public ?string $room = null; public int $state = self::OPEN; public function __construct(private FakeRelay $relay) { } public function control(array $message): void { if (($message['t'] ?? '') !== 'create') { return; } $room = (string)$message['room']; $this->room = $room; $this->peer = $this->relay->nextPeer++; $others = $this->relay->rooms[$room] ?? []; $this->relay->rooms[$room][$this->peer] = $this; $this->events[] = new Event(Event::ROOM, -1, (string)json_encode(['room' => $room, 'peer' => $this->peer, 'host' => $others === [] ? $this->peer : array_key_first($others), 'peers' => array_keys($others)])); foreach ($others as $other) { $other->events[] = new Event(Event::PEER_JOIN, $this->peer); } } public function createRoom(int $maxPeers = 8, array $meta = [], bool $public = false): void { } public function quickJoin(int $maxPeers = 8, array $meta = []): void { } public function lockRoom(bool $locked): void { } public function joinRoom(string $code): void { } public function leaveRoom(): void { $this->leave(); } public function setRoomInfo(array $info): void { } public function send(string $data, ?int $to = null, bool $reliable = true): bool { if ($this->room === null || $this->state !== self::OPEN) { return false; } $this->relay->traffic[] = $data; foreach ($this->relay->rooms[$this->room] ?? [] as $peer => $c) { if ($peer !== $this->peer && ($to === null || $to === $peer)) { $c->events[] = new Event(Event::MESSAGE, $this->peer, $data); } } return true; } public function ping(): void { } public function poll(): array { [$events, $this->events] = [$this->events, []]; return $events; } public function state(): int { return $this->state; } public function close(): void { $this->leave(); $this->state = self::CLOSED; } private function leave(): void { if ($this->room === null) { return; } unset($this->relay->rooms[$this->room][$this->peer]); foreach ($this->relay->rooms[$this->room] ?? [] as $c) { $c->events[] = new Event(Event::PEER_LEAVE, $this->peer); } $this->room = null; }}