laravel-websockets/src/Statistics/Logging/StatisticsLogger.php

72 lines
1.9 KiB
PHP
Raw Normal View History

2018-12-03 12:02:51 +00:00
<?php
namespace BeyondCode\LaravelWebSockets\Statistics\Logging;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Illuminate\Support\Collection;
use Ratchet\ConnectionInterface;
2018-12-03 13:07:18 +00:00
class StatisticsLogger
2018-12-03 12:02:51 +00:00
{
/** @var Statistic[] */
protected $statistics = [];
2018-12-03 12:57:01 +00:00
/** @var \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager */
2018-12-03 12:02:51 +00:00
protected $channelManager;
public function __construct(ChannelManager $channelManager)
{
$this->channelManager = $channelManager;
}
public function webSocketMessage(ConnectionInterface $connection)
{
$this->initializeStatistics($connection->app->id);
$this->statistics[$connection->app->id]->webSocketMessage();
}
2018-12-03 12:33:20 +00:00
public function apiMessage($appId)
2018-12-03 12:02:51 +00:00
{
2018-12-03 12:33:20 +00:00
$this->initializeStatistics($appId);
2018-12-03 12:02:51 +00:00
2018-12-03 12:33:20 +00:00
$this->statistics[$appId]->apiMessage();
2018-12-03 12:02:51 +00:00
}
public function connection(ConnectionInterface $connection)
{
$this->initializeStatistics($connection->app->id);
$this->statistics[$connection->app->id]->connection();
}
public function disconnection(ConnectionInterface $connection)
{
$this->initializeStatistics($connection->app->id);
$this->statistics[$connection->app->id]->disconnection();
}
protected function initializeStatistics($id)
{
2018-12-03 12:27:45 +00:00
if (!isset($this->statistics[$id])) {
2018-12-03 12:02:51 +00:00
$this->statistics[$id] = new Statistic($id);
}
}
public function save()
{
foreach ($this->statistics as $appId => $statistic) {
2018-12-03 12:37:30 +00:00
if ($statistic->isEnabled()) {
// TODO: perform http request
}
2018-12-03 12:02:51 +00:00
// Reset connection and message count
$connections = Collection::make($this->channelManager->getChannels($appId))->sum(function ($channel) {
return count($channel->getSubscribedConnections());
});
$statistic->reset($connections);
}
}
}