]>
Commit | Line | Data |
---|---|---|
b74b96bf | 1 | <?php |
3c66e564 | 2 | namespace Shaarli\Config; |
b74b96bf A |
3 | |
4 | /** | |
5 | * Class ConfigJson (ConfigIO implementation) | |
6 | * | |
7 | * Handle Shaarli's JSON configuration file. | |
8 | */ | |
9 | class ConfigJson implements ConfigIO | |
10 | { | |
b74b96bf A |
11 | /** |
12 | * @inheritdoc | |
13 | */ | |
93b1fe54 | 14 | public function read($filepath) |
b74b96bf | 15 | { |
da10377b | 16 | if (! is_readable($filepath)) { |
b74b96bf A |
17 | return array(); |
18 | } | |
19 | $data = file_get_contents($filepath); | |
da10377b | 20 | $data = str_replace(self::getPhpHeaders(), '', $data); |
5ff23f02 | 21 | $data = str_replace(self::getPhpSuffix(), '', $data); |
b74b96bf A |
22 | $data = json_decode($data, true); |
23 | if ($data === null) { | |
24 | $error = json_last_error(); | |
3c66e564 | 25 | throw new \Exception('An error occurred while parsing JSON file: error code #'. $error); |
b74b96bf A |
26 | } |
27 | return $data; | |
28 | } | |
29 | ||
30 | /** | |
31 | * @inheritdoc | |
32 | */ | |
93b1fe54 | 33 | public function write($filepath, $conf) |
b74b96bf A |
34 | { |
35 | // JSON_PRETTY_PRINT is available from PHP 5.4. | |
36 | $print = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0; | |
5ff23f02 | 37 | $data = self::getPhpHeaders() . json_encode($conf, $print) . self::getPhpSuffix(); |
b74b96bf | 38 | if (!file_put_contents($filepath, $data)) { |
3c66e564 | 39 | throw new \IOException( |
b74b96bf A |
40 | $filepath, |
41 | 'Shaarli could not create the config file. | |
42 | Please make sure Shaarli has the right to write in the folder is it installed in.' | |
43 | ); | |
44 | } | |
45 | } | |
46 | ||
47 | /** | |
48 | * @inheritdoc | |
49 | */ | |
93b1fe54 | 50 | public function getExtension() |
b74b96bf A |
51 | { |
52 | return '.json.php'; | |
53 | } | |
da10377b A |
54 | |
55 | /** | |
56 | * The JSON data is wrapped in a PHP file for security purpose. | |
57 | * This way, even if the file is accessible, credentials and configuration won't be exposed. | |
58 | * | |
59 | * Note: this isn't a static field because concatenation isn't supported in field declaration before PHP 5.6. | |
60 | * | |
61 | * @return string PHP start tag and comment tag. | |
62 | */ | |
63 | public static function getPhpHeaders() | |
64 | { | |
65 | return '<?php /*'. PHP_EOL; | |
66 | } | |
5ff23f02 A |
67 | |
68 | /** | |
69 | * Get PHP comment closing tags. | |
70 | * | |
71 | * Static method for consistency with getPhpHeaders. | |
72 | * | |
73 | * @return string PHP comment closing. | |
74 | */ | |
75 | public static function getPhpSuffix() | |
76 | { | |
77 | return PHP_EOL . '*/ ?>'; | |
78 | } | |
b74b96bf | 79 | } |