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