JsonFile.php 9.8 KB

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