diff --git a/src/ImmutableRecord.php b/src/ImmutableRecord.php index a705147..1e6022f 100644 --- a/src/ImmutableRecord.php +++ b/src/ImmutableRecord.php @@ -17,7 +17,7 @@ * @package EventEngine\Data * @psalm-immutable */ -interface ImmutableRecord +interface ImmutableRecord extends \JsonSerializable { const PHP_TYPE_STRING = 'string'; const PHP_TYPE_INT = 'int'; diff --git a/src/ImmutableRecordLogic.php b/src/ImmutableRecordLogic.php index 5516f05..f315893 100644 --- a/src/ImmutableRecordLogic.php +++ b/src/ImmutableRecordLogic.php @@ -139,6 +139,11 @@ public function equals(ImmutableRecord $other): bool return $this->toArray() === $other->toArray(); } + public function jsonSerialize(): array + { + return $this->toArray(); + } + private function setRecordData(array $recordData): void { foreach ($recordData as $key => $value) { diff --git a/tests/ImmutableRecordLogicTest.php b/tests/ImmutableRecordLogicTest.php index e8f9ab5..45d1516 100644 --- a/tests/ImmutableRecordLogicTest.php +++ b/tests/ImmutableRecordLogicTest.php @@ -266,4 +266,31 @@ public function it_throws_an_exception_if_no_type_hint_was_found() ImmutableRecordWithNoTypes::fromArray($this->data); } + + /** + * @test + */ + public function it_supports_json_serializable() + { + $record = TypeHintedImmutableRecordWithValueObjects::fromArray($this->data); + + $this->data['type'] = null; + $this->data['percentage'] = 0.5; + + $this->assertEquals( + $this->data, + $record->jsonSerialize() + ); + + $this->assertEquals( + $record->toArray(), + $record->jsonSerialize() + ); + + $json = json_encode($record); + $this->assertJson($json); + + $decoded = json_decode($json, true); + $this->assertEquals($this->data, $decoded); + } }