103 lines
2.5 KiB
PHP
103 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\React\CommandBus;
|
|
|
|
use JsonSerializable;
|
|
use Symfony\Component\Uid\Uuid;
|
|
|
|
/**
|
|
* A serializable message frame
|
|
*
|
|
*/
|
|
class Message implements JsonSerializable
|
|
{
|
|
/** @var string Execute request */
|
|
const MSGTYPE_EXECUTE = 'execute';
|
|
/** @var string Execute result */
|
|
const MSGTYPE_RESULT = 'result';
|
|
/** @var string Error message */
|
|
const MSGTYPE_ERROR = 'error';
|
|
/** @var string Notify event */
|
|
const MSGTYPE_NOTIFY = 'notify';
|
|
/** @var string Registry update (command list set and update) */
|
|
const MSGTYPE_REGISTRY = 'registry';
|
|
|
|
/** @var string $uuid The message identifier */
|
|
private string $uuid;
|
|
|
|
private string $messageType;
|
|
|
|
private array $messageData;
|
|
|
|
public function __construct(string $messageType, array $messageData = [], null|string|false $uuid = null)
|
|
{
|
|
$this->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
|
|
];
|
|
}
|
|
}
|
|
|