JsonFile.php 9.1 KB

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