From e1c3d8200bd45de385249a10b6bcfb5988bd0b80 Mon Sep 17 00:00:00 2001 From: Maciej Zgadzaj Date: Thu, 3 Dec 2020 11:55:16 +0100 Subject: [PATCH] [gps] Add support for consuming message from external publisher in non-standard format --- pkg/gps/GpsMessage.php | 8 ++------ pkg/gps/Tests/GpsMessageTest.php | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/pkg/gps/GpsMessage.php b/pkg/gps/GpsMessage.php index 5e83e078c..37a71b445 100644 --- a/pkg/gps/GpsMessage.php +++ b/pkg/gps/GpsMessage.php @@ -158,14 +158,10 @@ 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() - )); + 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 diff --git a/pkg/gps/Tests/GpsMessageTest.php b/pkg/gps/Tests/GpsMessageTest.php index d84cd99d9..a43a22315 100644 --- a/pkg/gps/Tests/GpsMessageTest.php +++ b/pkg/gps/Tests/GpsMessageTest.php @@ -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);