hyperf-chat/app/Support/SocketIOParser.php

41 lines
942 B
PHP
Raw Normal View History

2020-11-20 19:17:11 +08:00
<?php
namespace App\Support;
class SocketIOParser extends Packet
{
/**
* Encode output payload for websocket push.
*
* @param string $event
* @param mixed $data
*
* @return mixed
*/
public static function encode(string $event, $data)
{
$packet = Packet::MESSAGE . Packet::EVENT;
$shouldEncode = is_array($data) || is_object($data);
$data = $shouldEncode ? json_encode($data) : $data;
$format = $shouldEncode ? '["%s",%s]' : '["%s","%s"]';
return $packet . sprintf($format, $event, $data);
}
/**
* Decode message from websocket client.
*
2020-12-02 15:14:29 +08:00
* @param string $string
2020-11-20 19:17:11 +08:00
*
* @return array
*/
2020-12-02 15:14:29 +08:00
public static function decode($string)
2020-11-20 19:17:11 +08:00
{
2020-12-02 15:14:29 +08:00
$payload = Packet::getPayload($string);
2020-11-20 19:17:11 +08:00
return [
'event' => $payload['event'] ?? null,
'data' => $payload['data'] ?? null,
];
}
}