hyperf-chat/app/Support/SocketIOParser.php

42 lines
965 B
PHP
Raw Normal View History

2020-11-20 19:17:11 +08:00
<?php
2021-04-20 16:30:57 +08:00
2020-11-20 19:17:11 +08:00
namespace App\Support;
class SocketIOParser extends Packet
{
/**
* Encode output payload for websocket push.
*
* @param string $event
2021-04-20 16:30:57 +08:00
* @param mixed $data
2020-11-20 19:17:11 +08:00
*
* @return mixed
*/
public static function encode(string $event, $data)
{
2021-04-20 16:30:57 +08:00
$packet = Packet::MESSAGE . Packet::EVENT;
2020-11-20 19:17:11 +08:00
$shouldEncode = is_array($data) || is_object($data);
2021-04-20 16:30:57 +08:00
$data = $shouldEncode ? json_encode($data) : $data;
$format = $shouldEncode ? '["%s",%s]' : '["%s","%s"]';
2020-11-20 19:17:11 +08:00
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,
2021-04-20 16:30:57 +08:00
'data' => $payload['data'] ?? null,
2020-11-20 19:17:11 +08:00
];
}
}