ConfigJson.php 2.1 KB

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