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