]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/config/ConfigJson.php
Use the configuration manager for wallabag and readityourself plugin
[github/shaarli/Shaarli.git] / application / config / ConfigJson.php
CommitLineData
b74b96bf
A
1<?php
2
3/**
4 * Class ConfigJson (ConfigIO implementation)
5 *
6 * Handle Shaarli's JSON configuration file.
7 */
8class ConfigJson implements ConfigIO
9{
10 /**
11 * The JSON data is wrapped in a PHP file for security purpose.
12 * This way, even if the file is accessible, credentials and configuration won't be exposed.
13 *
14 * @var string PHP start tag and comment tag.
15 */
16 public static $PHP_HEADER;
17
18 public function __construct()
19 {
20 // The field can't be initialized directly with concatenation before PHP 5.6.
21 self::$PHP_HEADER = '<?php /*'. PHP_EOL;
22 }
23
24 /**
25 * @inheritdoc
26 */
27 function read($filepath)
28 {
29 if (! file_exists($filepath) || ! is_readable($filepath)) {
30 return array();
31 }
32 $data = file_get_contents($filepath);
33 $data = str_replace(self::$PHP_HEADER, '', $data);
34 $data = json_decode($data, true);
35 if ($data === null) {
36 $error = json_last_error();
37 throw new Exception('An error occured while parsing JSON file: error code #'. $error);
38 }
39 return $data;
40 }
41
42 /**
43 * @inheritdoc
44 */
45 function write($filepath, $conf)
46 {
47 // JSON_PRETTY_PRINT is available from PHP 5.4.
48 $print = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
49 $data = self::$PHP_HEADER . json_encode($conf, $print);
50 if (!file_put_contents($filepath, $data)) {
51 throw new IOException(
52 $filepath,
53 'Shaarli could not create the config file.
54 Please make sure Shaarli has the right to write in the folder is it installed in.'
55 );
56 }
57 }
58
59 /**
60 * @inheritdoc
61 */
62 function getExtension()
63 {
64 return '.json.php';
65 }
66}