JsonFile.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. use Composer\Composer;
  14. use JsonSchema\Validator;
  15. use Seld\JsonLint\JsonParser;
  16. use Composer\Util\StreamContextFactory;
  17. if (!defined('JSON_UNESCAPED_SLASHES')) {
  18. define('JSON_UNESCAPED_SLASHES', 64);
  19. }
  20. if (!defined('JSON_PRETTY_PRINT')) {
  21. define('JSON_PRETTY_PRINT', 128);
  22. }
  23. if (!defined('JSON_UNESCAPED_UNICODE')) {
  24. define('JSON_UNESCAPED_UNICODE', 256);
  25. }
  26. /**
  27. * Reads/writes json files.
  28. *
  29. * @author Konstantin Kudryashiv <ever.zet@gmail.com>
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. */
  32. class JsonFile
  33. {
  34. private $path;
  35. /**
  36. * Initializes json file reader/parser.
  37. *
  38. * @param string $lockFile path to a lockfile
  39. */
  40. public function __construct($path)
  41. {
  42. $this->path = $path;
  43. }
  44. public function getPath()
  45. {
  46. return $this->path;
  47. }
  48. /**
  49. * Checks whether json file exists.
  50. *
  51. * @return Boolean
  52. */
  53. public function exists()
  54. {
  55. return is_file($this->path);
  56. }
  57. /**
  58. * Reads json file.
  59. *
  60. * @return array
  61. */
  62. public function read()
  63. {
  64. $ctx = StreamContextFactory::getContext(array(
  65. 'http' => array(
  66. 'header' => 'User-Agent: Composer/'.Composer::VERSION."\r\n"
  67. )
  68. ));
  69. $json = file_get_contents($this->path, false, $ctx);
  70. if (!$json) {
  71. throw new \RuntimeException('Could not read '.$this->path.', you are probably offline');
  72. }
  73. return static::parseJson($json);
  74. }
  75. /**
  76. * Writes json file.
  77. *
  78. * @param array $hash writes hash into json file
  79. * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  80. */
  81. public function write(array $hash, $options = 448)
  82. {
  83. $dir = dirname($this->path);
  84. if (!is_dir($dir)) {
  85. if (file_exists($dir)) {
  86. throw new \UnexpectedValueException(
  87. $dir.' exists and is not a directory.'
  88. );
  89. }
  90. if (!mkdir($dir, 0777, true)) {
  91. throw new \UnexpectedValueException(
  92. $dir.' does not exist and could not be created.'
  93. );
  94. }
  95. }
  96. file_put_contents($this->path, static::encode($hash, $options). ($options & JSON_PRETTY_PRINT ? "\n" : ''));
  97. }
  98. /**
  99. * Validates the schema of the current json file according to composer-schema.json rules
  100. *
  101. * @param string $json
  102. * @return Boolean true on success
  103. * @throws \UnexpectedValueException
  104. */
  105. public function validateSchema()
  106. {
  107. $content = file_get_contents($this->path);
  108. $data = json_decode($content);
  109. if (null === $data && 'null' !== $content) {
  110. self::validateSyntax($content);
  111. }
  112. $schema = json_decode(file_get_contents(__DIR__ . '/../../../res/composer-schema.json'));
  113. $validator = new Validator();
  114. $validator->check($data, $schema);
  115. if (!$validator->isValid()) {
  116. $msg = "\n";
  117. foreach ((array) $validator->getErrors() as $error) {
  118. $msg .= ($error['property'] ? $error['property'].' : ' : '').$error['message']."\n";
  119. }
  120. throw new \UnexpectedValueException('Your composer.json is invalid. The following errors were found:' . $msg);
  121. }
  122. return true;
  123. }
  124. /**
  125. * Encodes an array into (optionally pretty-printed) JSON
  126. *
  127. * This code is based on the function found at:
  128. * http://recursive-design.com/blog/2008/03/11/format-json-with-php/
  129. *
  130. * @param mixed $data Data to encode into a formatted JSON string
  131. * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  132. * @return string Encoded json
  133. */
  134. static public function encode($data, $options = 448)
  135. {
  136. if (version_compare(PHP_VERSION, '5.4', '>=')) {
  137. return json_encode($data, $options);
  138. }
  139. $json = json_encode($data);
  140. $prettyPrint = (Boolean) ($options & JSON_PRETTY_PRINT);
  141. $unescapeUnicode = (Boolean) ($options & JSON_UNESCAPED_UNICODE);
  142. $unescapeSlashes = (Boolean) ($options & JSON_UNESCAPED_SLASHES);
  143. if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes) {
  144. return $json;
  145. }
  146. $result = '';
  147. $pos = 0;
  148. $strLen = strlen($json);
  149. $indentStr = ' ';
  150. $newLine = "\n";
  151. $outOfQuotes = true;
  152. $buffer = '';
  153. $noescape = true;
  154. for ($i = 0; $i <= $strLen; $i++) {
  155. // Grab the next character in the string
  156. $char = substr($json, $i, 1);
  157. // Are we inside a quoted string?
  158. if ('"' === $char && $noescape) {
  159. $outOfQuotes = !$outOfQuotes;
  160. }
  161. if (!$outOfQuotes) {
  162. $buffer .= $char;
  163. $noescape = '\\' === $char ? !$noescape : true;
  164. continue;
  165. } elseif ('' !== $buffer) {
  166. if ($unescapeSlashes) {
  167. $buffer = str_replace('\\/', '/', $buffer);
  168. }
  169. if ($unescapeUnicode && function_exists('mb_convert_encoding')) {
  170. // http://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
  171. $buffer = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($match) {
  172. return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
  173. }, $buffer);
  174. }
  175. $result .= $buffer.$char;
  176. $buffer = '';
  177. continue;
  178. }
  179. if (':' === $char) {
  180. // Add a space after the : character
  181. $char .= ' ';
  182. } elseif (('}' === $char || ']' === $char)) {
  183. $pos--;
  184. $prevChar = substr($json, $i - 1, 1);
  185. if ('{' !== $prevChar && '[' !== $prevChar) {
  186. // If this character is the end of an element,
  187. // output a new line and indent the next line
  188. $result .= $newLine;
  189. for ($j = 0; $j < $pos; $j++) {
  190. $result .= $indentStr;
  191. }
  192. } else {
  193. // Collapse empty {} and []
  194. $result = rtrim($result);
  195. }
  196. }
  197. $result .= $char;
  198. // If the last character was the beginning of an element,
  199. // output a new line and indent the next line
  200. if (',' === $char || '{' === $char || '[' === $char) {
  201. $result .= $newLine;
  202. if ('{' === $char || '[' === $char) {
  203. $pos++;
  204. }
  205. for ($j = 0; $j < $pos; $j++) {
  206. $result .= $indentStr;
  207. }
  208. }
  209. }
  210. return $result;
  211. }
  212. /**
  213. * Parses json string and returns hash.
  214. *
  215. * @param string $json json string
  216. *
  217. * @return mixed
  218. */
  219. public static function parseJson($json)
  220. {
  221. $data = json_decode($json, true);
  222. if (null === $data && 'null' !== $json) {
  223. self::validateSyntax($json);
  224. }
  225. return $data;
  226. }
  227. /**
  228. * Validates the syntax of a JSON string
  229. *
  230. * @param string $json
  231. * @return Boolean true on success
  232. * @throws \UnexpectedValueException
  233. */
  234. protected static function validateSyntax($json)
  235. {
  236. $parser = new JsonParser();
  237. $result = $parser->lint($json);
  238. if (null === $result) {
  239. return true;
  240. }
  241. throw $result;
  242. }
  243. }