Skip to content

Commit

Permalink
[10.x] add Storage::json() method to read and decode a json file (#46548
Browse files Browse the repository at this point in the history
)

* add FilesystemAdapter::json() method to read and decode a json file

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
lorenzolosa and taylorotwell committed Mar 22, 2023
1 parent 51f8524 commit 706a076
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Illuminate/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,15 @@ public function get($path, $lock = false)
* Get the contents of a file as decoded JSON.
*
* @param string $path
* @param int $flags
* @param bool $lock
* @return array
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function json($path, $lock = false)
public function json($path, $flags = 0, $lock = false)
{
return json_decode($this->get($path, $lock), true);
return json_decode($this->get($path, $lock), true, 512, $flags);
}

/**
Expand Down
14 changes: 14 additions & 0 deletions src/Illuminate/Filesystem/FilesystemAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,20 @@ public function get($path)
}
}

/**
* Get the contents of a file as decoded JSON.
*
* @param string $path
* @param int $flags
* @return array|null
*/
public function json($path, $flags = 0)
{
$content = $this->get($path);

return is_null($content) ? null : json_decode($content, true, 512, $flags);
}

/**
* Create a streamed response for a given file.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Filesystem/FilesystemAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,20 @@ public function testGetFileNotFound()
$this->assertNull($filesystemAdapter->get('file.txt'));
}

public function testJsonReturnsDecodedJsonData()
{
$this->filesystem->write('file.json', '{"foo": "bar"}');
$filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter);
$this->assertSame(['foo' => 'bar'], $filesystemAdapter->json('file.json'));
}

public function testJsonReturnsNullIfJsonDataIsInvalid()
{
$this->filesystem->write('file.json', '{"foo":');
$filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter);
$this->assertNull($filesystemAdapter->json('file.json'));
}

public function testMimeTypeNotDetected()
{
$this->filesystem->write('unknown.mime-type', '');
Expand Down

0 comments on commit 706a076

Please sign in to comment.