name = $name ?: uniqid("group"); } public function add(WebSocketInterface $connection): void { if (in_array($connection, $this->connections)) return; $this->connections[] = $connection; $this->emit(self::EVENT_JOIN, [ $this->name, $connection ]); } public function remove(WebSocketInterface $connection): void { if (!in_array($connection, $this->connections)) return; $this->connections = array_filter($this->connections, fn($other) => $other != $connection); $this->emit(self::EVENT_LEAVE, [ $this->name, $connection ]); } public function count(): int { return count($this->connections); } /** * * @return \Traversable */ public function getIterator(): Traversable { return new ArrayIterator($this->connections); } /** * * @return WebSocketInterface[] */ public function getAll(): array { return $this->connections; } public function getName(): string { return $this->name; } public function writeAll(string $payload) { foreach ($this->connections as $connection) { if ($connection->isWritable()) { $connection->write($payload); } } } /** * * @return void */ public function closeAll(string $reason, int $code=1001) { foreach ($this->connections as $connection) { $connection->closeWithReason($reason, $code); } } }