Skip to content

Commit ffe8590

Browse files
author
Maciej Zgadzaj
committed
[gps] Add support for consuming message from external publisher in non-standard format
1 parent 7d3da26 commit ffe8590

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

pkg/gps/GpsMessage.php

+3-7
Original file line numberDiff line numberDiff line change
@@ -157,15 +157,11 @@ public function jsonSerialize(): array
157157
public static function jsonUnserialize(string $json): self
158158
{
159159
$data = json_decode($json, true);
160-
if (JSON_ERROR_NONE !== json_last_error()) {
161-
throw new \InvalidArgumentException(sprintf(
162-
'The malformed json given. Error %s and message %s',
163-
json_last_error(),
164-
json_last_error_msg()
165-
));
160+
if (\JSON_ERROR_NONE !== json_last_error()) {
161+
throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
166162
}
167163

168-
return new self($data['body'], $data['properties'], $data['headers']);
164+
return new self($data['body'] ?? $json, $data['properties'] ?? [], $data['headers'] ?? []);
169165
}
170166

171167
public function getNativeMessage(): ?GoogleMessage

pkg/gps/Tests/GpsMessageTest.php

+25
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,31 @@ public function testCouldBeUnserializedFromJson()
3838
$this->assertEquals($message, $unserializedMessage);
3939
}
4040

41+
public function testMessageEntityCouldBeUnserializedFromJson()
42+
{
43+
$json = '{"body":"theBody","properties":{"thePropFoo":"thePropFooVal"},"headers":{"theHeaderFoo":"theHeaderFooVal"}}';
44+
45+
$unserializedMessage = GpsMessage::jsonUnserialize($json);
46+
47+
$this->assertInstanceOf(GpsMessage::class, $unserializedMessage);
48+
$decoded = json_decode($json, true);
49+
$this->assertEquals($decoded['body'], $unserializedMessage->getBody());
50+
$this->assertEquals($decoded['properties'], $unserializedMessage->getProperties());
51+
$this->assertEquals($decoded['headers'], $unserializedMessage->getHeaders());
52+
}
53+
54+
public function testMessagePayloadCouldBeUnserializedFromJson()
55+
{
56+
$json = '{"theBodyPropFoo":"theBodyPropVal"}';
57+
58+
$unserializedMessage = GpsMessage::jsonUnserialize($json);
59+
60+
$this->assertInstanceOf(GpsMessage::class, $unserializedMessage);
61+
$this->assertEquals($json, $unserializedMessage->getBody());
62+
$this->assertEquals([], $unserializedMessage->getProperties());
63+
$this->assertEquals([], $unserializedMessage->getHeaders());
64+
}
65+
4166
public function testThrowIfMalformedJsonGivenOnUnsterilizedFromJson()
4267
{
4368
$this->expectException(\InvalidArgumentException::class);

0 commit comments

Comments
 (0)