uuid = ($uuid===null) ? (string)Uuid::v7() : $uuid; $this->messageType = $messageType; $this->messageData = $messageData; } public function getUuid(): string { return $this->uuid ? $this->uuid : ""; } public function getType(): string { return $this->messageType; } public function getData(): array { return $this->messageData; } /** * * @param string $data The JSON-encoded message data * @return Message * @throws MessageException if the message can not be parsed */ public static function fromString(string $data): Message { $json = @json_decode($data, true); if (!$json || empty($json['msg'])) { throw new MessageException("Invalid data"); } return new Message($json['msg'], $json['data'], $json['uuid']??false); } public static function fromStringMulti(string $data): array { return array_map(fn($v) => Message::fromString($v), array_filter(explode("\n", $data))); } public function asResult($result): Message { return new Message(self::MSGTYPE_RESULT, [ 'result' => $result ], $this->uuid); } public function asError($error): Message { return new Message(self::MSGTYPE_ERROR, [ 'error' => $error ], $this->uuid); } public function toJson(): string { return json_encode($this, JSON_UNESCAPED_SLASHES); } public function jsonSerialize(): array { return [ 'uuid' => $this->uuid, 'msg' => $this->messageType, 'data' => $this->messageData ]; } }