JsonFile.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 JsonSchema\Validator;
  13. use Seld\JsonLint\JsonParser;
  14. use Seld\JsonLint\ParsingException;
  15. use Composer\Util\RemoteFilesystem;
  16. use Composer\Downloader\TransportException;
  17. /**
  18. * Reads/writes json files.
  19. *
  20. * @author Konstantin Kudryashiv <ever.zet@gmail.com>
  21. * @author Jordi Boggiano <j.boggiano@seld.be>
  22. */
  23. class JsonFile
  24. {
  25. const LAX_SCHEMA = 1;
  26. const STRICT_SCHEMA = 2;
  27. const JSON_UNESCAPED_SLASHES = 64;
  28. const JSON_PRETTY_PRINT = 128;
  29. const JSON_UNESCAPED_UNICODE = 256;
  30. private $path;
  31. private $rfs;
  32. /**
  33. * Initializes json file reader/parser.
  34. *
  35. * @param string $path path to a lockfile
  36. * @param RemoteFilesystem $rfs required for loading http/https json files
  37. * @throws \InvalidArgumentException
  38. */
  39. public function __construct($path, RemoteFilesystem $rfs = null)
  40. {
  41. $this->path = $path;
  42. if (null === $rfs && preg_match('{^https?://}i', $path)) {
  43. throw new \InvalidArgumentException('http urls require a RemoteFilesystem instance to be passed');
  44. }
  45. $this->rfs = $rfs;
  46. }
  47. /**
  48. * @return string
  49. */
  50. public function getPath()
  51. {
  52. return $this->path;
  53. }
  54. /**
  55. * Checks whether json file exists.
  56. *
  57. * @return bool
  58. */
  59. public function exists()
  60. {
  61. return is_file($this->path);
  62. }
  63. /**
  64. * Reads json file.
  65. *
  66. * @throws \RuntimeException
  67. * @return mixed
  68. */
  69. public function read()
  70. {
  71. try {
  72. if ($this->rfs) {
  73. $json = $this->rfs->getContents($this->path, $this->path, false);
  74. } else {
  75. $json = file_get_contents($this->path);
  76. }
  77. } catch (TransportException $e) {
  78. throw new \RuntimeException($e->getMessage(), 0, $e);
  79. } catch (\Exception $e) {
  80. throw new \RuntimeException('Could not read '.$this->path."\n\n".$e->getMessage());
  81. }
  82. return static::parseJson($json, $this->path);
  83. }
  84. /**
  85. * Writes json file.
  86. *
  87. * @param array $hash writes hash into json file
  88. * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  89. * @throws \UnexpectedValueException
  90. */
  91. public function write(array $hash, $options = 448)
  92. {
  93. $dir = dirname($this->path);
  94. if (!is_dir($dir)) {
  95. if (file_exists($dir)) {
  96. throw new \UnexpectedValueException(
  97. $dir.' exists and is not a directory.'
  98. );
  99. }
  100. if (!@mkdir($dir, 0777, true)) {
  101. throw new \UnexpectedValueException(
  102. $dir.' does not exist and could not be created.'
  103. );
  104. }
  105. }
  106. $retries = 3;
  107. while ($retries--) {
  108. try {
  109. file_put_contents($this->path, static::encode($hash, $options). ($options & self::JSON_PRETTY_PRINT ? "\n" : ''));
  110. break;
  111. } catch (\Exception $e) {
  112. if ($retries) {
  113. usleep(500000);
  114. continue;
  115. }
  116. throw $e;
  117. }
  118. }
  119. }
  120. /**
  121. * Validates the schema of the current json file according to composer-schema.json rules
  122. *
  123. * @param int $schema a JsonFile::*_SCHEMA constant
  124. * @return bool true on success
  125. * @throws JsonValidationException
  126. */
  127. public function validateSchema($schema = self::STRICT_SCHEMA)
  128. {
  129. $content = file_get_contents($this->path);
  130. $data = json_decode($content);
  131. if (null === $data && 'null' !== $content) {
  132. self::validateSyntax($content, $this->path);
  133. }
  134. $schemaFile = __DIR__ . '/../../../res/composer-schema.json';
  135. $schemaData = json_decode(file_get_contents($schemaFile));
  136. if ($schema === self::LAX_SCHEMA) {
  137. $schemaData->additionalProperties = true;
  138. $schemaData->required = array();
  139. }
  140. $validator = new Validator();
  141. $validator->check($data, $schemaData);
  142. // TODO add more validation like check version constraints and such, perhaps build that into the arrayloader?
  143. if (!$validator->isValid()) {
  144. $errors = array();
  145. foreach ((array) $validator->getErrors() as $error) {
  146. $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message'];
  147. }
  148. throw new JsonValidationException('"'.$this->path.'" does not match the expected JSON schema', $errors);
  149. }
  150. return true;
  151. }
  152. /**
  153. * Encodes an array into (optionally pretty-printed) JSON
  154. *
  155. * @param mixed $data Data to encode into a formatted JSON string
  156. * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  157. * @return string Encoded json
  158. */
  159. public static function encode($data, $options = 448)
  160. {
  161. if (PHP_VERSION_ID >= 50400) {
  162. $json = json_encode($data, $options);
  163. if (false === $json) {
  164. self::throwEncodeError(json_last_error());
  165. }
  166. // compact brackets to follow recent php versions
  167. if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) {
  168. $json = preg_replace('/\[\s+\]/', '[]', $json);
  169. $json = preg_replace('/\{\s+\}/', '{}', $json);
  170. }
  171. return $json;
  172. }
  173. $json = json_encode($data);
  174. if (false === $json) {
  175. self::throwEncodeError(json_last_error());
  176. }
  177. $prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT);
  178. $unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE);
  179. $unescapeSlashes = (bool) ($options & self::JSON_UNESCAPED_SLASHES);
  180. if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes) {
  181. return $json;
  182. }
  183. $result = JsonFormatter::format($json, $unescapeUnicode, $unescapeSlashes);
  184. return $result;
  185. }
  186. /**
  187. * Throws an exception according to a given code with a customized message
  188. *
  189. * @param int $code return code of json_last_error function
  190. * @throws \RuntimeException
  191. */
  192. private static function throwEncodeError($code)
  193. {
  194. switch ($code) {
  195. case JSON_ERROR_DEPTH:
  196. $msg = 'Maximum stack depth exceeded';
  197. break;
  198. case JSON_ERROR_STATE_MISMATCH:
  199. $msg = 'Underflow or the modes mismatch';
  200. break;
  201. case JSON_ERROR_CTRL_CHAR:
  202. $msg = 'Unexpected control character found';
  203. break;
  204. case JSON_ERROR_UTF8:
  205. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  206. break;
  207. default:
  208. $msg = 'Unknown error';
  209. }
  210. throw new \RuntimeException('JSON encoding failed: '.$msg);
  211. }
  212. /**
  213. * Parses json string and returns hash.
  214. *
  215. * @param string $json json string
  216. * @param string $file the json file
  217. *
  218. * @return mixed
  219. */
  220. public static function parseJson($json, $file = null)
  221. {
  222. if (null === $json) {
  223. return;
  224. }
  225. $data = json_decode($json, true);
  226. if (null === $data && JSON_ERROR_NONE !== json_last_error()) {
  227. self::validateSyntax($json, $file);
  228. }
  229. return $data;
  230. }
  231. /**
  232. * Validates the syntax of a JSON string
  233. *
  234. * @param string $json
  235. * @param string $file
  236. * @return bool true on success
  237. * @throws \UnexpectedValueException
  238. * @throws JsonValidationException
  239. * @throws ParsingException
  240. */
  241. protected static function validateSyntax($json, $file = null)
  242. {
  243. $parser = new JsonParser();
  244. $result = $parser->lint($json);
  245. if (null === $result) {
  246. if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) {
  247. throw new \UnexpectedValueException('"'.$file.'" is not UTF-8, could not parse as JSON');
  248. }
  249. return true;
  250. }
  251. throw new ParsingException('"'.$file.'" does not contain valid JSON'."\n".$result->getMessage(), $result->getDetails());
  252. }
  253. }