Skip to content

Commit abb8215

Browse files
Merge pull request #59 from kojirock5260/feature/allow_array_serialize
allow array serialize
2 parents 81aef30 + 576cd2b commit abb8215

File tree

2 files changed

+59
-8
lines changed

2 files changed

+59
-8
lines changed

src/Drivers/JsonDriver.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,16 @@
44

55
use PHPUnit\Framework\Assert;
66
use Spatie\Snapshots\Driver;
7-
use Spatie\Snapshots\Exceptions\CantBeSerialized;
87

98
class JsonDriver implements Driver
109
{
1110
public function serialize($data): string
1211
{
13-
if (! is_string($data)) {
14-
throw new CantBeSerialized('Only strings can be serialized to json');
12+
if (is_string($data)) {
13+
$data = json_decode($data, true);
1514
}
1615

17-
return json_encode(json_decode($data), JSON_PRETTY_PRINT).PHP_EOL;
16+
return json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;
1817
}
1918

2019
public function extension(): string

tests/Unit/Drivers/JsonDriverTest.php

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

55
use PHPUnit\Framework\TestCase;
66
use Spatie\Snapshots\Drivers\JsonDriver;
7-
use Spatie\Snapshots\Exceptions\CantBeSerialized;
87

98
class JsonDriverTest extends TestCase
109
{
@@ -24,12 +23,65 @@ public function it_can_serialize_a_json_string_to_pretty_json()
2423
}
2524

2625
/** @test */
27-
public function it_can_only_serialize_strings()
26+
public function it_can_serialize_a_json_hash_to_pretty_json()
2827
{
2928
$driver = new JsonDriver();
3029

31-
$this->expectException(CantBeSerialized::class);
30+
$expected = implode(PHP_EOL, [
31+
'{',
32+
' "foo": "FOO",',
33+
' "bar": "BAR",',
34+
' "baz": "BAZ"',
35+
'}',
36+
'',
37+
]);
38+
$this->assertEquals($expected, $driver->serialize([
39+
'foo' => 'FOO',
40+
'bar' => 'BAR',
41+
'baz' => 'BAZ',
42+
]));
43+
44+
$expected = implode(PHP_EOL, [
45+
'{',
46+
' "foo": "FOO",',
47+
' "bar": "BAR",',
48+
' "baz": {',
49+
' "aaa": "AAA",',
50+
' "bbb": "BBB",',
51+
' "ccc": [',
52+
' "xxx",',
53+
' "yyy",',
54+
' "zzz"',
55+
' ]',
56+
' }',
57+
'}',
58+
'',
59+
]);
60+
$this->assertEquals($expected, $driver->serialize([
61+
'foo' => 'FOO',
62+
'bar' => 'BAR',
63+
'baz' => [
64+
'aaa' => 'AAA',
65+
'bbb' => 'BBB',
66+
'ccc' => ['xxx', 'yyy', 'zzz'],
67+
],
68+
]));
69+
}
70+
71+
/** @test */
72+
public function it_can_serialize_a_json_array_to_pretty_json()
73+
{
74+
$driver = new JsonDriver();
75+
76+
$expected = implode(PHP_EOL, [
77+
'[',
78+
' "foo",',
79+
' "bar",',
80+
' "baz"',
81+
']',
82+
'',
83+
]);
3284

33-
$driver->serialize(['foo' => 'bar']);
85+
$this->assertEquals($expected, $driver->serialize(['foo', 'bar', 'baz']));
3486
}
3587
}

0 commit comments

Comments
 (0)