diff --git a/src/Drivers/JsonDriver.php b/src/Drivers/JsonDriver.php index 41e22cd..6f3d4d8 100644 --- a/src/Drivers/JsonDriver.php +++ b/src/Drivers/JsonDriver.php @@ -11,11 +11,11 @@ class JsonDriver implements Driver public function serialize($data): string { if (is_string($data)) { - $data = json_decode($data, true); + $data = json_decode($data); } - if (! is_array($data)) { - throw new CantBeSerialized('Only strings can be serialized to json'); + if (is_resource($data)) { + throw new CantBeSerialized('Resources can not be serialized to json'); } return json_encode($data, JSON_PRETTY_PRINT).PHP_EOL; diff --git a/tests/Unit/Drivers/JsonDriverTest.php b/tests/Unit/Drivers/JsonDriverTest.php index 1af3253..7e8ab85 100644 --- a/tests/Unit/Drivers/JsonDriverTest.php +++ b/tests/Unit/Drivers/JsonDriverTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Spatie\Snapshots\Drivers\JsonDriver; +use Spatie\Snapshots\Exceptions\CantBeSerialized; class JsonDriverTest extends TestCase { @@ -84,4 +85,39 @@ public function it_can_serialize_a_json_array_to_pretty_json() $this->assertEquals($expected, $driver->serialize(['foo', 'bar', 'baz'])); } + + /** @test */ + public function it_can_serialize_a_empty_json_object_to_pretty_json() + { + $driver = new JsonDriver(); + + $expected = implode(PHP_EOL, [ + '{', + ' "foo": {', + ' "bar": true', + ' },', + ' "baz": {}', + '}', + '', + ]); + + $this->assertEquals($expected, $driver->serialize((object) [ + 'foo' => (object) [ + 'bar' => true, + ], + 'baz' => (object) [], + ])); + } + + /** @test */ + public function it_can_not_serialize_resources() + { + $driver = new JsonDriver(); + + $this->expectException(CantBeSerialized::class); + + $resource = fopen('.', 'r'); + + $driver->serialize($resource); + } }