channelManager = $channelManager; $this->browser = $browser; } public function webSocketMessage(ConnectionInterface $connection) { $this ->findOrMakeStatisticForAppId($connection->app->id) ->webSocketMessage(); } public function apiMessage($appId) { $this ->findOrMakeStatisticForAppId($appId) ->apiMessage(); } public function connection(ConnectionInterface $connection) { $this ->findOrMakeStatisticForAppId($connection->app->id) ->connection(); } public function disconnection(ConnectionInterface $connection) { $this ->findOrMakeStatisticForAppId($connection->app->id) ->disconnection(); } protected function findOrMakeStatisticForAppId($appId): Statistic { if (! isset($this->statistics[$appId])) { $this->statistics[$appId] = new Statistic($appId); } return $this->statistics[$appId]; } public function save() { foreach ($this->statistics as $appId => $statistic) { if (! $statistic->isEnabled()) { continue; } $this->browser ->post( action([WebSocketStatisticsEntriesController::class, 'store']), ['Content-Type' => 'application/json'], stream_for(json_encode($statistic->toArray())) ); // Reset connection and message count $currentConnectionCount = collect($this->channelManager->getChannels($appId)) ->sum(function ($channel) { return count($channel->getSubscribedConnections()); }); $statistic->reset($currentConnectionCount); } } }