Empty json objects encoded as arrays
Closed this issue · 3 comments
Hi,
When an empty object is used it is been serialised and snapshotted as an array, for example this will fail once the snapshot is created:
public function testJsonSnapshot()
{
$json = json_encode((object) [
'data' => [
'objectData' => (object)[]
]
]);
// dump($json);
// {"data":{"objectData":{}}}
$this->assertMatchesJsonSnapshot($json);
// snapshot contents
/*
{
"data": {
"objectData": []
}
}
*/
}
basically []
in the snapshot vs {}
in the $json variable
Paul
pretty sure its because of JSON_PRETTY_PRINT
and this might be the answer but not sure where it should be fixed? https://www.php.net/manual/en/json.constants.php#constant.json-force-object
ok, its the true parameter of this line https://github.com/spatie/phpunit-snapshot-assertions/blob/master/src/Drivers/JsonDriver.php#L14
however removing that causes an error with json that has an object at the root level because of https://github.com/spatie/phpunit-snapshot-assertions/blob/master/src/Drivers/JsonDriver.php#L17
so its fixable with something like:
public function serialize($data): string
{
if (is_string($data)) {
$data = json_decode($data);
}
if (! is_array($data) && !is_object($data)) {
throw new CantBeSerialized('Only strings can be serialized to json');
}
return json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;
}
but that will be a breaking change for any existing snapshots, and i dont know what the original context of limiting what can be serialized to json was?