Skip to content

Commit

Permalink
[gps] Add support for consuming message from external publisher in no…
Browse files Browse the repository at this point in the history
…n-standard format
  • Loading branch information
Maciej Zgadzaj committed Mar 23, 2021
1 parent 7d3da26 commit ffe8590
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
10 changes: 3 additions & 7 deletions pkg/gps/GpsMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,11 @@ public function jsonSerialize(): array
public static function jsonUnserialize(string $json): self
{
$data = json_decode($json, 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()
));
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 self($data['body'], $data['properties'], $data['headers']);
return new self($data['body'] ?? $json, $data['properties'] ?? [], $data['headers'] ?? []);
}

public function getNativeMessage(): ?GoogleMessage
Expand Down
25 changes: 25 additions & 0 deletions pkg/gps/Tests/GpsMessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,31 @@ public function testCouldBeUnserializedFromJson()
$this->assertEquals($message, $unserializedMessage);
}

public function testMessageEntityCouldBeUnserializedFromJson()
{
$json = '{"body":"theBody","properties":{"thePropFoo":"thePropFooVal"},"headers":{"theHeaderFoo":"theHeaderFooVal"}}';

$unserializedMessage = GpsMessage::jsonUnserialize($json);

$this->assertInstanceOf(GpsMessage::class, $unserializedMessage);
$decoded = json_decode($json, true);
$this->assertEquals($decoded['body'], $unserializedMessage->getBody());
$this->assertEquals($decoded['properties'], $unserializedMessage->getProperties());
$this->assertEquals($decoded['headers'], $unserializedMessage->getHeaders());
}

public function testMessagePayloadCouldBeUnserializedFromJson()
{
$json = '{"theBodyPropFoo":"theBodyPropVal"}';

$unserializedMessage = GpsMessage::jsonUnserialize($json);

$this->assertInstanceOf(GpsMessage::class, $unserializedMessage);
$this->assertEquals($json, $unserializedMessage->getBody());
$this->assertEquals([], $unserializedMessage->getProperties());
$this->assertEquals([], $unserializedMessage->getHeaders());
}

public function testThrowIfMalformedJsonGivenOnUnsterilizedFromJson()
{
$this->expectException(\InvalidArgumentException::class);
Expand Down

0 comments on commit ffe8590

Please sign in to comment.