Lines 100.00% 11 / 11
Methods 100.00% 3 / 3
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 createForPublish 100.00% 7 / 7 100.00% 1 / 1 7
 decodeJsonPayload 100.00% 3 / 3 100.00% 1 / 1 2
11final readonly class MqttMessage
12{
13    private const int MAX_TOPIC_BYTES = 65535;
14
15    public function __construct(
16        public string $topic,
17        public string $payload,
18        public MqttQos $qos = MqttQos::AtMostOnce,
19        public bool $retain = false,
20    ) {}
21
22    /**
23     * @param string|array<array-key, mixed> $payload
24     * @throws MqttException
25     */
26    public static function createForPublish(string $topic, string|array $payload, MqttQos $qos, bool $retain): self
27    {
28        if ($topic === '' || \strlen($topic) > self::MAX_TOPIC_BYTES || strpbrk($topic, "+#\0") !== false || preg_match('//u', $topic) !== 1) {
29            throw MqttException::createForReason(MqttError::TopicInvalid, topic: $topic);
30        }
31
32        if (\is_string($payload)) {
33            return new self($topic, $payload, $qos, $retain);
34        }
35
36        try {
37            return new self($topic, json_encode($payload, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE), $qos, $retain);
38        } catch (JsonException $e) {
39            throw MqttException::createForReason(MqttError::PayloadUnencodable, $e, topic: $topic);
40        }
41    }
42
43    /** @throws MqttException */
44    public function decodeJsonPayload(): mixed
45    {
46        try {
47            return json_decode($this->payload, true, flags: \JSON_THROW_ON_ERROR);
48        } catch (JsonException $e) {
49            throw MqttException::createForReason(MqttError::PayloadNotJson, $e, topic: $this->topic);
50        }
51    }
52}