Skip to content

Commit

Permalink
File::json() method to get json decoded data from a file. (#46481)
Browse files Browse the repository at this point in the history
* Adds File::json() method to get json decoded data from a file.

* Update Filesystem.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
AustinW and taylorotwell committed Mar 16, 2023
1 parent 5c17d5b commit 960adb5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
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

0 comments on commit 960adb5

Please sign in to comment.