diff --git a/src/Illuminate/Filesystem/Filesystem.php b/src/Illuminate/Filesystem/Filesystem.php index 7f5b01354362..b15ee1c6d633 100644 --- a/src/Illuminate/Filesystem/Filesystem.php +++ b/src/Illuminate/Filesystem/Filesystem.php @@ -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. * diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index f061c5bb575a..3d3dba7651fd 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -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');