JsonFile.php 9.9 KB

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