Files
react-websocket/src/Group/GroupManager.php

54 lines
1.6 KiB
PHP
Raw Normal View History

2024-02-21 03:03:08 +01:00
<?php
namespace NoccyLabs\React\WebSocket\Group;
2024-02-21 22:43:31 +01:00
use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
2024-02-21 03:03:08 +01:00
use React\EventLoop\Loop;
2024-02-21 22:43:31 +01:00
class GroupManager implements EventEmitterInterface
2024-02-21 03:03:08 +01:00
{
2024-02-21 22:43:31 +01:00
use EventEmitterTrait;
2024-02-21 23:48:13 +01:00
/**
* @var string emitted when a new group is created
*/
2024-02-22 02:01:12 +01:00
const EVENT_CREATE = 'create';
2024-02-21 23:48:13 +01:00
/**
* @var string emitted after the last member leaves, when the group is destroyed
*/
2024-02-22 02:01:12 +01:00
const EVENT_DESTROY = 'destroy';
2024-02-21 22:43:31 +01:00
2024-02-21 03:03:08 +01:00
/** @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) {
2024-02-22 02:01:12 +01:00
$this->emit(self::EVENT_DESTROY, [ $group ]);
2024-02-21 03:03:08 +01:00
$group->removeAllListeners();
unset($this->groups[$group->getName()]);
}
});
});
2024-02-22 02:01:12 +01:00
$this->emit(self::EVENT_CREATE, [ $group ]);
2024-02-21 03:03:08 +01:00
} else {
$group = $this->groups[$name];
}
return $group;
}
public function closeAll(string $reason, int $code=1001)
{
foreach ($this->groups as $group) {
$group->closeAll($reason, $code);
}
}
2024-02-21 03:03:08 +01:00
}