JsonFile.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Json;
  12. use Composer\Repository\RepositoryManager;
  13. /**
  14. * Reads/writes json files.
  15. *
  16. * @author Konstantin Kudryashiv <ever.zet@gmail.com>
  17. */
  18. class JsonFile
  19. {
  20. private $path;
  21. /**
  22. * Initializes json file reader/parser.
  23. *
  24. * @param string $lockFile path to a lockfile
  25. */
  26. public function __construct($path)
  27. {
  28. $this->path = $path;
  29. }
  30. /**
  31. * Checks whether json file exists.
  32. *
  33. * @return Boolean
  34. */
  35. public function exists()
  36. {
  37. return is_file($this->path);
  38. }
  39. /**
  40. * Reads json file.
  41. *
  42. * @param string $json path or json string
  43. *
  44. * @return array
  45. */
  46. public function read()
  47. {
  48. $json = file_get_contents($this->path);
  49. return static::parseJson($json);
  50. }
  51. /**
  52. * Writes json file.
  53. *
  54. * @param array $hash writes hash into json file
  55. */
  56. public function write(array $hash)
  57. {
  58. file_put_contents($this->path, json_encode($hash));
  59. }
  60. /**
  61. * Parses json string and returns hash.
  62. *
  63. * @param string $json json string
  64. *
  65. * @return array
  66. */
  67. public static function parseJson($json)
  68. {
  69. $hash = json_decode($json, true);
  70. if (!$hash) {
  71. switch (json_last_error()) {
  72. case JSON_ERROR_NONE:
  73. $msg = 'No error has occurred, is your composer.json file empty?';
  74. break;
  75. case JSON_ERROR_DEPTH:
  76. $msg = 'The maximum stack depth has been exceeded';
  77. break;
  78. case JSON_ERROR_STATE_MISMATCH:
  79. $msg = 'Invalid or malformed JSON';
  80. break;
  81. case JSON_ERROR_CTRL_CHAR:
  82. $msg = 'Control character error, possibly incorrectly encoded';
  83. break;
  84. case JSON_ERROR_SYNTAX:
  85. $msg = 'Syntax error';
  86. break;
  87. case JSON_ERROR_UTF8:
  88. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  89. break;
  90. }
  91. throw new \UnexpectedValueException('Incorrect composer.json file: '.$msg);
  92. }
  93. return $hash;
  94. }
  95. }