Skip to content

Commit 04b5372

Browse files
Merge pull request #74 from mintbridge/master
correct json driver to not force all objects to arrays (in particular…
2 parents 810ff69 + db640df commit 04b5372

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/Drivers/JsonDriver.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ class JsonDriver implements Driver
1111
public function serialize($data): string
1212
{
1313
if (is_string($data)) {
14-
$data = json_decode($data, true);
14+
$data = json_decode($data);
1515
}
1616

17-
if (! is_array($data)) {
18-
throw new CantBeSerialized('Only strings can be serialized to json');
17+
if (is_resource($data)) {
18+
throw new CantBeSerialized('Resources can not be serialized to json');
1919
}
2020

2121
return json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;

tests/Unit/Drivers/JsonDriverTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PHPUnit\Framework\TestCase;
66
use Spatie\Snapshots\Drivers\JsonDriver;
7+
use Spatie\Snapshots\Exceptions\CantBeSerialized;
78

89
class JsonDriverTest extends TestCase
910
{
@@ -84,4 +85,39 @@ public function it_can_serialize_a_json_array_to_pretty_json()
8485

8586
$this->assertEquals($expected, $driver->serialize(['foo', 'bar', 'baz']));
8687
}
88+
89+
/** @test */
90+
public function it_can_serialize_a_empty_json_object_to_pretty_json()
91+
{
92+
$driver = new JsonDriver();
93+
94+
$expected = implode(PHP_EOL, [
95+
'{',
96+
' "foo": {',
97+
' "bar": true',
98+
' },',
99+
' "baz": {}',
100+
'}',
101+
'',
102+
]);
103+
104+
$this->assertEquals($expected, $driver->serialize((object) [
105+
'foo' => (object) [
106+
'bar' => true,
107+
],
108+
'baz' => (object) [],
109+
]));
110+
}
111+
112+
/** @test */
113+
public function it_can_not_serialize_resources()
114+
{
115+
$driver = new JsonDriver();
116+
117+
$this->expectException(CantBeSerialized::class);
118+
119+
$resource = fopen('.', 'r');
120+
121+
$driver->serialize($resource);
122+
}
87123
}

0 commit comments

Comments
 (0)