JsonFile.php 9.3 KB

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