Skip to content

Commit

Permalink
Merge pull request #74 from mintbridge/master
Browse files Browse the repository at this point in the history
correct json driver to not force all objects to arrays (in particular…
  • Loading branch information
sebastiandedeyne committed Nov 22, 2019
2 parents 810ff69 + db640df commit 04b5372
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
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);
}
}

0 comments on commit 04b5372

Please sign in to comment.