react-websocket/src/Group/ConnectionGroup.php

68 lines
1.6 KiB
PHP

<?php
namespace NoccyLabs\React\WebSocket\Group;
use ArrayIterator;
use Countable;
use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
use IteratorAggregate;
use NoccyLabs\React\WebSocket\WebSocketInterface;
use Traversable;
class ConnectionGroup implements EventEmitterInterface, IteratorAggregate, Countable
{
const EVENT_JOIN = 'join';
const EVENT_LEAVE = 'leave';
use EventEmitterTrait;
private string $name;
/** @var WebSocketInterface[] */
private array $connections = [];
public function __construct(?string $name = null)
{
$this->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);
}
public function getIterator(): Traversable
{
return new ArrayIterator($this->connections);
}
public function getAll(): array
{
return $this->connections;
}
public function getName(): string
{
return $this->name;
}
public function write(string $payload)
{
}
}