Skip to content

Commit d1758ea

Browse files
author
Greg Bowler
committed
test: DataObject::jsonSerialize()
1 parent 4954ae4 commit d1758ea

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/DataObject.php

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ public function typeof(string $name):?string {
8686
}
8787
}
8888

89+
/** @noinspection PhpMixedReturnTypeCanBeReducedInspection - This allows php.gt/json to extend and return primitives */
8990
public function jsonSerialize():mixed {
9091
return $this->asArray();
9192
}

test/phpunit/DataObjectTest.php

+29
Original file line numberDiff line numberDiff line change
@@ -311,4 +311,33 @@ public function testTypeof() {
311311
self::assertEquals("null", $sut->typeof("nothing"));
312312
self::assertNull($sut->typeof("address"));
313313
}
314+
315+
public function testJsonSerialize() {
316+
$obj = new StdClass();
317+
$obj->nestedKey = "nestedValue";
318+
$dateTime = new DateTime();
319+
320+
$sut = (new DataObject())
321+
->with("name", "example")
322+
->with("id", 123)
323+
->with("size", 2_347.467)
324+
->with("isSecure", true)
325+
->with("container", $obj)
326+
->with("dispatchDate", $dateTime)
327+
->with("nothing", null);
328+
$json = json_encode($sut);
329+
330+
self::assertStringContainsString('"name":"example"', $json);
331+
self::assertStringContainsString('"id":123', $json);
332+
self::assertStringContainsString('"size":2347.467', $json);
333+
self::assertStringContainsString('"isSecure":true', $json);
334+
self::assertStringContainsString('"container":{"nestedKey":"nestedValue"}', $json);
335+
self::assertStringContainsString('"nothing":null', $json);
336+
337+
$obj = json_decode($json);
338+
self::assertStringContainsString(
339+
$dateTime->format("Y-m-d H:i:s.u"),
340+
$obj->dispatchDate->date
341+
);
342+
}
314343
}

0 commit comments

Comments
 (0)