Skip to content

Commit a3b3f30

Browse files
authored
Merge pull request #22 from event-engine/feature/json-serializable
feat: Add support for json serializable
2 parents bdba5b0 + 7e9af7c commit a3b3f30

3 files changed

Lines changed: 33 additions & 1 deletion

File tree

src/ImmutableRecord.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
* @package EventEngine\Data
1818
* @psalm-immutable
1919
*/
20-
interface ImmutableRecord
20+
interface ImmutableRecord extends \JsonSerializable
2121
{
2222
const PHP_TYPE_STRING = 'string';
2323
const PHP_TYPE_INT = 'int';

src/ImmutableRecordLogic.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ public function equals(ImmutableRecord $other): bool
139139
return $this->toArray() === $other->toArray();
140140
}
141141

142+
public function jsonSerialize(): array
143+
{
144+
return $this->toArray();
145+
}
146+
142147
private function setRecordData(array $recordData): void
143148
{
144149
foreach ($recordData as $key => $value) {

tests/ImmutableRecordLogicTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,4 +266,31 @@ public function it_throws_an_exception_if_no_type_hint_was_found()
266266

267267
ImmutableRecordWithNoTypes::fromArray($this->data);
268268
}
269+
270+
/**
271+
* @test
272+
*/
273+
public function it_supports_json_serializable()
274+
{
275+
$record = TypeHintedImmutableRecordWithValueObjects::fromArray($this->data);
276+
277+
$this->data['type'] = null;
278+
$this->data['percentage'] = 0.5;
279+
280+
$this->assertEquals(
281+
$this->data,
282+
$record->jsonSerialize()
283+
);
284+
285+
$this->assertEquals(
286+
$record->toArray(),
287+
$record->jsonSerialize()
288+
);
289+
290+
$json = json_encode($record);
291+
$this->assertJson($json);
292+
293+
$decoded = json_decode($json, true);
294+
$this->assertEquals($this->data, $decoded);
295+
}
269296
}

0 commit comments

Comments
 (0)