]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/config/ConfigJson.php
Merge pull request #788 from virtualtam/application/namespace/config
[github/shaarli/Shaarli.git] / application / config / ConfigJson.php
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 $error = json_last_error();
25 throw new \Exception('An error occurred while parsing JSON file: error code #'. $error);
26 }
27 return $data;
28 }
29
30 /**
31 * @inheritdoc
32 */
33 public function write($filepath, $conf)
34 {
35 // JSON_PRETTY_PRINT is available from PHP 5.4.
36 $print = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
37 $data = self::getPhpHeaders() . json_encode($conf, $print) . self::getPhpSuffix();
38 if (!file_put_contents($filepath, $data)) {
39 throw new \IOException(
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 */
50 public function getExtension()
51 {
52 return '.json.php';
53 }
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 }
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 }
79 }