tapi/app/entity/gateway/ws/OutMessage.php
2025-08-29 23:54:17 +08:00

48 lines
1.3 KiB
PHP

<?php
namespace app\entity\gateway\ws;
use app\entity\gateway\script\BaseScript;
use app\enum\gateway\message\{ScriptEnum, SystemEnum};
class OutMessage
{
private string $type;
private string $event;
private array $data;
public function __construct(
BaseScript|ScriptEnum|SystemEnum|array $event,
mixed $data = []
)
{
// 通过Base::create();创建的
if (is_array($event) && count($event) == 3) {
$this->type = $event[0];
$this->event = $event[1];
$this->data = $event[2];
return;
} else if ($event instanceof ScriptEnum) {
$this->type = 'script';
$this->event = $event->value;
} else if ($event instanceof SystemEnum) {
$this->type = 'system';
$this->event = $event->value;
}
// data处理
if ($data instanceof BaseScript) {
$this->data = $data->toArray();
} else {
$this->data = (array)$data;
}
}
public function toJson(): string
{
return json_encode([
'type' => $this->type,
'event' => $this->event,
'data' => $this->data,
], JSON_UNESCAPED_UNICODE);
}
}