JsonFile.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. // Prepend with file:// only when not using a special schema already (e.g. in the phar)
  143. if (false === strpos($schemaFile, '://')) {
  144. $schemaFile = 'file://' . $schemaFile;
  145. }
  146. $schemaData = (object) array('$ref' => $schemaFile);
  147. if ($schema === self::LAX_SCHEMA) {
  148. $schemaData->additionalProperties = true;
  149. $schemaData->required = array();
  150. }
  151. $validator = new Validator();
  152. $validator->check($data, $schemaData);
  153. // TODO add more validation like check version constraints and such, perhaps build that into the arrayloader?
  154. if (!$validator->isValid()) {
  155. $errors = array();
  156. foreach ((array) $validator->getErrors() as $error) {
  157. $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message'];
  158. }
  159. throw new JsonValidationException('"'.$this->path.'" does not match the expected JSON schema', $errors);
  160. }
  161. return true;
  162. }
  163. /**
  164. * Encodes an array into (optionally pretty-printed) JSON
  165. *
  166. * @param mixed $data Data to encode into a formatted JSON string
  167. * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  168. * @return string Encoded json
  169. */
  170. public static function encode($data, $options = 448)
  171. {
  172. if (PHP_VERSION_ID >= 50400) {
  173. $json = json_encode($data, $options);
  174. if (false === $json) {
  175. self::throwEncodeError(json_last_error());
  176. }
  177. // compact brackets to follow recent php versions
  178. if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) {
  179. $json = preg_replace('/\[\s+\]/', '[]', $json);
  180. $json = preg_replace('/\{\s+\}/', '{}', $json);
  181. }
  182. return $json;
  183. }
  184. $json = json_encode($data);
  185. if (false === $json) {
  186. self::throwEncodeError(json_last_error());
  187. }
  188. $prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT);
  189. $unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE);
  190. $unescapeSlashes = (bool) ($options & self::JSON_UNESCAPED_SLASHES);
  191. if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes) {
  192. return $json;
  193. }
  194. $result = JsonFormatter::format($json, $unescapeUnicode, $unescapeSlashes);
  195. return $result;
  196. }
  197. /**
  198. * Throws an exception according to a given code with a customized message
  199. *
  200. * @param int $code return code of json_last_error function
  201. * @throws \RuntimeException
  202. */
  203. private static function throwEncodeError($code)
  204. {
  205. switch ($code) {
  206. case JSON_ERROR_DEPTH:
  207. $msg = 'Maximum stack depth exceeded';
  208. break;
  209. case JSON_ERROR_STATE_MISMATCH:
  210. $msg = 'Underflow or the modes mismatch';
  211. break;
  212. case JSON_ERROR_CTRL_CHAR:
  213. $msg = 'Unexpected control character found';
  214. break;
  215. case JSON_ERROR_UTF8:
  216. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  217. break;
  218. default:
  219. $msg = 'Unknown error';
  220. }
  221. throw new \RuntimeException('JSON encoding failed: '.$msg);
  222. }
  223. /**
  224. * Parses json string and returns hash.
  225. *
  226. * @param string $json json string
  227. * @param string $file the json file
  228. *
  229. * @return mixed
  230. */
  231. public static function parseJson($json, $file = null)
  232. {
  233. if (null === $json) {
  234. return;
  235. }
  236. $data = json_decode($json, true);
  237. if (null === $data && JSON_ERROR_NONE !== json_last_error()) {
  238. self::validateSyntax($json, $file);
  239. }
  240. return $data;
  241. }
  242. /**
  243. * Validates the syntax of a JSON string
  244. *
  245. * @param string $json
  246. * @param string $file
  247. * @throws \UnexpectedValueException
  248. * @throws JsonValidationException
  249. * @throws ParsingException
  250. * @return bool true on success
  251. */
  252. protected static function validateSyntax($json, $file = null)
  253. {
  254. $parser = new JsonParser();
  255. $result = $parser->lint($json);
  256. if (null === $result) {
  257. if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) {
  258. throw new \UnexpectedValueException('"'.$file.'" is not UTF-8, could not parse as JSON');
  259. }
  260. return true;
  261. }
  262. throw new ParsingException('"'.$file.'" does not contain valid JSON'."\n".$result->getMessage(), $result->getDetails());
  263. }
  264. }