Skip to content

Commit 367e4d4

Browse files
committed
alow array serialize
1 parent 81aef30 commit 367e4d4

File tree

2 files changed

+59
-6
lines changed

2 files changed

+59
-6
lines changed

src/Drivers/JsonDriver.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ class JsonDriver implements Driver
1010
{
1111
public function serialize($data): string
1212
{
13-
if (! is_string($data)) {
14-
throw new CantBeSerialized('Only strings can be serialized to json');
13+
if (is_string($data)) {
14+
$data = json_decode($data, true);
1515
}
1616

17-
return json_encode(json_decode($data), JSON_PRETTY_PRINT).PHP_EOL;
17+
return json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;
1818
}
1919

2020
public function extension(): string

tests/Unit/Drivers/JsonDriverTest.php

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,65 @@ public function it_can_serialize_a_json_string_to_pretty_json()
2424
}
2525

2626
/** @test */
27-
public function it_can_only_serialize_strings()
27+
public function it_can_serialize_a_json_hash_to_pretty_json()
2828
{
2929
$driver = new JsonDriver();
3030

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

33-
$driver->serialize(['foo' => 'bar']);
86+
$this->assertEquals($expected, $driver->serialize(['foo', 'bar', 'baz']));
3487
}
3588
}

0 commit comments

Comments
 (0)