Skip to content

Commit 02efabe

Browse files
Add JsonDriver validation
1 parent abb8215 commit 02efabe

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/Drivers/JsonDriver.php

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

55
use PHPUnit\Framework\Assert;
66
use Spatie\Snapshots\Driver;
7+
use Spatie\Snapshots\Exceptions\CantBeSerialized;
78

89
class JsonDriver implements Driver
910
{
@@ -13,6 +14,10 @@ public function serialize($data): string
1314
$data = json_decode($data, true);
1415
}
1516

17+
if (! is_array($data)) {
18+
throw new CantBeSerialized('Only strings can be serialized to json');
19+
}
20+
1621
return json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;
1722
}
1823

tests/Unit/Drivers/JsonDriverTest.php

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

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

810
class JsonDriverTest extends TestCase
911
{
@@ -84,4 +86,14 @@ public function it_can_serialize_a_json_array_to_pretty_json()
8486

8587
$this->assertEquals($expected, $driver->serialize(['foo', 'bar', 'baz']));
8688
}
89+
90+
/** @test */
91+
public function it_can_only_serialize_strings_and_arrays()
92+
{
93+
$this->expectException(CantBeSerialized::class);
94+
95+
$driver = new JsonDriver();
96+
97+
$driver->serialize(new stdClass);
98+
}
8799
}

0 commit comments

Comments
 (0)