ConfigJson.php 2.6 KB

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