react-websocket/src/Group/GroupManager.php

48 lines
1.4 KiB
PHP

<?php
namespace NoccyLabs\React\WebSocket\Group;
use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
use React\EventLoop\Loop;
class GroupManager implements EventEmitterInterface
{
use EventEmitterTrait;
/**
* @var string emitted when a new group is created
*/
const EVENT_CREATED = 'created';
/**
* @var string emitted after the last member leaves, when the group is destroyed
*/
const EVENT_DESTROYED = 'destroyed';
/** @var array<string,ConnectionGroup> */
private array $groups = [];
public function getConnectionGroup(string $name): ConnectionGroup
{
if (!array_key_exists($name, $this->groups)) {
$group = new ConnectionGroup($name);
$this->groups[$name] = $group;
// Clean up group when the last member leaves
$group->on(ConnectionGroup::EVENT_LEAVE, function () use ($group) {
Loop::futureTick(function () use ($group) {
if (count($group) === 0) {
$this->emit(self::EVENT_DESTROYED, [ $group ]);
$group->removeAllListeners();
unset($this->groups[$group->getName()]);
}
});
});
$this->emit(self::EVENT_CREATED, [ $group ]);
} else {
$group = $this->groups[$name];
}
return $group;
}
}