Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

correct json driver to not force all objects to arrays (in particular… #74

Merged
merged 2 commits into from Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Drivers/JsonDriver.php
Expand Up @@ -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;
Expand Down
36 changes: 36 additions & 0 deletions tests/Unit/Drivers/JsonDriverTest.php
Expand Up @@ -4,6 +4,7 @@

use PHPUnit\Framework\TestCase;
use Spatie\Snapshots\Drivers\JsonDriver;
use Spatie\Snapshots\Exceptions\CantBeSerialized;

class JsonDriverTest extends TestCase
{
Expand Down Expand Up @@ -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);
}
}