Initial commit
This commit is contained in:
63
src/Group/ConnectionGroup.php
Normal file
63
src/Group/ConnectionGroup.php
Normal file
@ -0,0 +1,63 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user