forked from yii2tech/filedb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileManagerJson.php
53 lines (47 loc) · 1.29 KB
/
FileManagerJson.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
/**
* @link https://github.com/yii2tech
* @copyright Copyright (c) 2015 Yii2tech
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace yii2tech\filedb;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\helpers\Json;
/**
* FileManagerJson performs data storage using JSON format.
*
* @author Paul Klimov <[email protected]>
* @since 1.0
*/
class FileManagerJson extends FileManager
{
/**
* @var string data file extension to be used.
*/
public $fileExtension = 'json';
/**
* @inheritdoc
*/
public function readData($fileName)
{
$fileName = $this->composeActualFileName($fileName);
if (!is_file($fileName)) {
throw new InvalidConfigException("File '{$fileName}' does not exist.");
}
$content = file_get_contents($fileName);
return Json::decode($content);
}
/**
* @inheritdoc
*/
public function writeData($fileName, array $data)
{
$fileName = $this->composeActualFileName($fileName);
$content = Json::encode($data);
$bytesWritten = file_put_contents($fileName, $content);
if ($bytesWritten <= 0) {
throw new Exception("Unable to write file '{$fileName}'.");
}
}
}