public function onMessage(WebSocketConnection $connection, $msg)
 {
     $message = \Blackjack\json_parse($msg);
     if (!isset($message['alias'])) {
         return;
     }
     $alias = $message['alias'];
     if ($alias === 'subscribe') {
         if ($this->isSubscribed($connection) || !isset($message['table_id'])) {
             $connection->close();
             return;
         }
         $tableId = $message['table_id'];
         /** @var WebSocketObservableTable $table */
         $table = $this->tableManager->getTableById($tableId);
         if ($table === null) {
             return;
         }
         $this->subscribe($connection, $table);
         return;
     }
     if ($alias === 'unsubscribe') {
         if (!$this->isSubscribed($connection)) {
             return;
         }
         $this->unsubscribe($connection);
         return;
     }
     if ($alias === 'query') {
         $connection->send(json_encode(['alias' => 'tables', 'data' => ['tables' => $this->tableManager->getTables()->map(function (Table $table) {
             return ['id' => $table->getId(), 'players' => $table->getSeats()->filter(function (TableSeat $seat) {
                 return $seat->getPlayer() !== null;
             })->map(function (TableSeat $seat) {
                 return ['player' => $seat->getPlayer()->getName()];
             })->elements()];
         })->elements()]]));
         return;
     }
 }
 /**
  * Watch for incoming data.
  *
  * @param Connection $connection
  */
 private function handleSocketEvents(Connection $connection)
 {
     $buffer = '';
     $connection->getSocket()->on('data', function ($data) use(&$buffer, $connection) {
         $buffer .= $data;
         while (($newlinePosition = strpos($buffer, "\n")) !== false) {
             $jsonMessage = substr($buffer, 0, $newlinePosition);
             $buffer = substr($buffer, $newlinePosition + 1);
             try {
                 $connection->setLastMessageReceivedAt(new \DateTime());
                 $message = $this->deserializer->deserialize(\Blackjack\json_parse($jsonMessage));
                 $connection->notify($message);
             } catch (\Exception $e) {
                 // Invalid message
                 $connection->getSocket()->write(json_encode(['alias' => 'invalid_message']));
                 $connection->getSocket()->close();
                 return;
             }
         }
         // Limit buffer to 1 MB
         $bufferSizeLimit = 1024 * 1024;
         if (strlen($buffer) > $bufferSizeLimit) {
             $buffer = substr($buffer, strlen($buffer) - $bufferSizeLimit);
         }
     });
     $connection->getSocket()->on('close', function () use($connection) {
         $this->handlePlayerDisconnection($connection);
     });
 }