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

File::json() method to get json decoded data from a file. #46481

Merged
merged 2 commits into from
Mar 16, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Illuminate/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ public function get($path, $lock = false)
throw new FileNotFoundException("File does not exist at path {$path}.");
}

/**
* Get the contents of a file as decoded JSON.
*
* @param string $path
* @param bool $lock
* @return array
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function json($path, $lock = false)
{
return json_decode($this->get($path, $lock), true);
}

/**
* Get contents of a file with shared access.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Filesystem/FilesystemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,20 @@ public function testGetRequireThrowsExceptionNonExistingFile()
$files->getRequire(self::$tempDir.'/file.php');
}

public function testJsonReturnsDecodedJsonData()
{
file_put_contents(self::$tempDir.'/file.json', '{"foo": "bar"}');
$files = new Filesystem;
$this->assertSame(['foo' => 'bar'], $files->json(self::$tempDir.'/file.json'));
}

public function testJsonReturnsNullIfJsonDataIsInvalid()
{
file_put_contents(self::$tempDir.'/file.json', '{"foo":');
$files = new Filesystem;
$this->assertNull($files->json(self::$tempDir . '/file.json'));
}

public function testAppendAddsDataToFile()
{
file_put_contents(self::$tempDir.'/file.txt', 'foo');
Expand Down