forked from php-enqueue/rdkafka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonSerializer.php
41 lines (34 loc) · 1.13 KB
/
JsonSerializer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
declare(strict_types=1);
namespace Enqueue\RdKafka;
class JsonSerializer implements Serializer
{
public function toString(RdKafkaMessage $message): string
{
$json = json_encode([
'body' => $message->getBody(),
'properties' => $message->getProperties(),
'headers' => $message->getHeaders(),
]);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(sprintf(
'The malformed json given. Error %s and message %s',
json_last_error(),
json_last_error_msg()
));
}
return $json;
}
public function toMessage(string $string): RdKafkaMessage
{
$data = json_decode($string, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(sprintf(
'The malformed json given. Error %s and message %s',
json_last_error(),
json_last_error_msg()
));
}
return new RdKafkaMessage($data['body'], $data['properties'], $data['headers']);
}
}