]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/config/ConfigJson.php
namespacing: \Shaarli\Exceptions\IOException
[github/shaarli/Shaarli.git] / application / config / ConfigJson.php
CommitLineData
b74b96bf 1<?php
3c66e564 2namespace Shaarli\Config;
b74b96bf
A
3
4/**
5 * Class ConfigJson (ConfigIO implementation)
6 *
7 * Handle Shaarli's JSON configuration file.
8 */
9class 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) {
c6a4c288 24 $errorCode = json_last_error();
12266213
A
25 $error = sprintf(
26 'An error occurred while parsing JSON configuration file (%s): error code #%d',
27 $filepath,
28 $errorCode
29 );
30 $error .= '<br>➜ <code>' . json_last_error_msg() .'</code>';
c6a4c288 31 if ($errorCode === JSON_ERROR_SYNTAX) {
12266213
A
32 $error .= '<br>';
33 $error .= 'Please check your JSON syntax (without PHP comment tags) using a JSON lint tool such as ';
c6a4c288
A
34 $error .= '<a href="http://jsonlint.com/">jsonlint.com</a>.';
35 }
36 throw new \Exception($error);
b74b96bf
A
37 }
38 return $data;
39 }
40
41 /**
42 * @inheritdoc
43 */
93b1fe54 44 public function write($filepath, $conf)
b74b96bf
A
45 {
46 // JSON_PRETTY_PRINT is available from PHP 5.4.
47 $print = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
5ff23f02 48 $data = self::getPhpHeaders() . json_encode($conf, $print) . self::getPhpSuffix();
b74b96bf 49 if (!file_put_contents($filepath, $data)) {
f3d2f257 50 throw new \Shaarli\Exceptions\IOException(
b74b96bf 51 $filepath,
12266213
A
52 t('Shaarli could not create the config file. '.
53 'Please make sure Shaarli has the right to write in the folder is it installed in.')
b74b96bf
A
54 );
55 }
56 }
57
58 /**
59 * @inheritdoc
60 */
93b1fe54 61 public function getExtension()
b74b96bf
A
62 {
63 return '.json.php';
64 }
da10377b
A
65
66 /**
67 * The JSON data is wrapped in a PHP file for security purpose.
68 * This way, even if the file is accessible, credentials and configuration won't be exposed.
69 *
70 * Note: this isn't a static field because concatenation isn't supported in field declaration before PHP 5.6.
71 *
72 * @return string PHP start tag and comment tag.
73 */
74 public static function getPhpHeaders()
75 {
76 return '<?php /*'. PHP_EOL;
77 }
5ff23f02
A
78
79 /**
80 * Get PHP comment closing tags.
81 *
82 * Static method for consistency with getPhpHeaders.
83 *
84 * @return string PHP comment closing.
85 */
86 public static function getPhpSuffix()
87 {
88 return PHP_EOL . '*/ ?>';
89 }
b74b96bf 90}