JsonManipulator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. /**
  13. * @author Jordi Boggiano <j.boggiano@seld.be>
  14. */
  15. class JsonManipulator
  16. {
  17. private static $RECURSE_BLOCKS;
  18. private static $JSON_VALUE;
  19. private static $JSON_STRING;
  20. private $contents;
  21. private $newline;
  22. private $indent;
  23. public function __construct($contents)
  24. {
  25. if (!self::$RECURSE_BLOCKS) {
  26. self::$RECURSE_BLOCKS = '(?:[^{}]*|\{(?:[^{}]*|\{(?:[^{}]*|\{(?:[^{}]*|\{[^{}]*\})*\})*\})*\})*';
  27. self::$JSON_STRING = '"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\0-\x09\x0a-\x1f\\\\"])*"';
  28. self::$JSON_VALUE = '(?:[0-9.]+|null|true|false|'.self::$JSON_STRING.'|\[[^\]]*\]|\{'.self::$RECURSE_BLOCKS.'\})';
  29. }
  30. $contents = trim($contents);
  31. if (!preg_match('#^\{(.*)\}$#s', $contents)) {
  32. throw new \InvalidArgumentException('The json file must be an object ({})');
  33. }
  34. $this->newline = false !== strpos($contents, "\r\n") ? "\r\n": "\n";
  35. $this->contents = $contents === '{}' ? '{' . $this->newline . '}' : $contents;
  36. $this->detectIndenting();
  37. }
  38. public function getContents()
  39. {
  40. return $this->contents . $this->newline;
  41. }
  42. public function addLink($type, $package, $constraint)
  43. {
  44. // no link of that type yet
  45. if (!preg_match('#"'.$type.'":\s*\{#', $this->contents)) {
  46. $this->addMainKey($type, array($package => $constraint));
  47. return true;
  48. }
  49. $linksRegex = '#("'.$type.'":\s*\{)([^}]+)(\})#s';
  50. if (!preg_match($linksRegex, $this->contents, $match)) {
  51. return false;
  52. }
  53. $links = $match[2];
  54. $packageRegex = str_replace('/', '\\\\?/', preg_quote($package));
  55. // link exists already
  56. if (preg_match('{"'.$packageRegex.'"\s*:}i', $links)) {
  57. $links = preg_replace('{"'.$packageRegex.'"(\s*:\s*)"[^"]+"}i', addcslashes(JsonFile::encode($package).'${1}"'.$constraint.'"', '\\'), $links);
  58. } elseif (preg_match('#[^\s](\s*)$#', $links, $match)) {
  59. // link missing but non empty links
  60. $links = preg_replace(
  61. '#'.$match[1].'$#',
  62. addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $match[1], '\\'),
  63. $links
  64. );
  65. } else {
  66. // links empty
  67. $links = $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $links;
  68. }
  69. $this->contents = preg_replace($linksRegex, addcslashes('${1}'.$links.'$3', '\\'), $this->contents);
  70. return true;
  71. }
  72. public function addRepository($name, $config)
  73. {
  74. return $this->addSubNode('repositories', $name, $config);
  75. }
  76. public function removeRepository($name)
  77. {
  78. return $this->removeSubNode('repositories', $name);
  79. }
  80. public function addConfigSetting($name, $value)
  81. {
  82. return $this->addSubNode('config', $name, $value);
  83. }
  84. public function removeConfigSetting($name)
  85. {
  86. return $this->removeSubNode('config', $name);
  87. }
  88. public function addSubNode($mainNode, $name, $value)
  89. {
  90. // no main node yet
  91. if (!preg_match('#"'.$mainNode.'":\s*\{#', $this->contents)) {
  92. $this->addMainKey(''.$mainNode.'', array($name => $value));
  93. return true;
  94. }
  95. $subName = null;
  96. if (false !== strpos($name, '.')) {
  97. list($name, $subName) = explode('.', $name, 2);
  98. }
  99. // main node content not match-able
  100. $nodeRegex = '#("'.$mainNode.'":\s*\{)('.self::$RECURSE_BLOCKS.')(\})#s';
  101. if (!preg_match($nodeRegex, $this->contents, $match)) {
  102. return false;
  103. }
  104. $children = $match[2];
  105. // invalid match due to un-regexable content, abort
  106. if (!json_decode('{'.$children.'}')) {
  107. return false;
  108. }
  109. $that = $this;
  110. // child exists
  111. if (preg_match('{("'.preg_quote($name).'"\s*:\s*)('.self::$JSON_VALUE.')(,?)}', $children, $matches)) {
  112. $children = preg_replace_callback('{("'.preg_quote($name).'"\s*:\s*)('.self::$JSON_VALUE.')(,?)}', function ($matches) use ($name, $subName, $value, $that) {
  113. if ($subName !== null) {
  114. $curVal = json_decode($matches[2], true);
  115. $curVal[$subName] = $value;
  116. $value = $curVal;
  117. }
  118. return $matches[1] . $that->format($value, 1) . $matches[3];
  119. }, $children);
  120. } elseif (preg_match('#[^\s](\s*)$#', $children, $match)) {
  121. if ($subName !== null) {
  122. $value = array($subName => $value);
  123. }
  124. // child missing but non empty children
  125. $children = preg_replace(
  126. '#'.$match[1].'$#',
  127. addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $match[1], '\\'),
  128. $children
  129. );
  130. } else {
  131. if ($subName !== null) {
  132. $value = array($subName => $value);
  133. }
  134. // children present but empty
  135. $children = $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $children;
  136. }
  137. $this->contents = preg_replace($nodeRegex, addcslashes('${1}'.$children.'$3', '\\'), $this->contents);
  138. return true;
  139. }
  140. public function removeSubNode($mainNode, $name)
  141. {
  142. // no node
  143. if (!preg_match('#"'.$mainNode.'":\s*\{#', $this->contents)) {
  144. return true;
  145. }
  146. // empty node
  147. if (preg_match('#"'.$mainNode.'":\s*\{\s*\}#s', $this->contents)) {
  148. return true;
  149. }
  150. // no node content match-able
  151. $nodeRegex = '#("'.$mainNode.'":\s*\{)('.self::$RECURSE_BLOCKS.')(\})#s';
  152. if (!preg_match($nodeRegex, $this->contents, $match)) {
  153. return false;
  154. }
  155. $children = $match[2];
  156. // invalid match due to un-regexable content, abort
  157. if (!json_decode('{'.$children.'}')) {
  158. return false;
  159. }
  160. $subName = null;
  161. if (false !== strpos($name, '.')) {
  162. list($name, $subName) = explode('.', $name, 2);
  163. }
  164. // try and find a match for the subkey
  165. if (preg_match('{"'.preg_quote($name).'"\s*:}i', $children)) {
  166. // find best match for the value of "name"
  167. if (preg_match_all('{"'.preg_quote($name).'"\s*:\s*(?:'.self::$JSON_VALUE.')}', $children, $matches)) {
  168. $bestMatch = '';
  169. foreach ($matches[0] as $match) {
  170. if (strlen($bestMatch) < strlen($match)) {
  171. $bestMatch = $match;
  172. }
  173. }
  174. $childrenClean = preg_replace('{,\s*'.preg_quote($bestMatch).'}i', '', $children, -1, $count);
  175. if (1 !== $count) {
  176. $childrenClean = preg_replace('{'.preg_quote($bestMatch).'\s*,?\s*}i', '', $childrenClean, -1, $count);
  177. if (1 !== $count) {
  178. return false;
  179. }
  180. }
  181. }
  182. }
  183. // no child data left, $name was the only key in
  184. if (!trim($childrenClean)) {
  185. $this->contents = preg_replace($nodeRegex, '$1'.$this->newline.$this->indent.'}', $this->contents);
  186. // we have a subname, so we restore the rest of $name
  187. if ($subName !== null) {
  188. $curVal = json_decode('{'.$children.'}', true);
  189. unset($curVal[$name][$subName]);
  190. $this->addSubNode($mainNode, $name, $curVal[$name]);
  191. }
  192. return true;
  193. }
  194. $that = $this;
  195. $this->contents = preg_replace_callback($nodeRegex, function ($matches) use ($that, $name, $subName, $childrenClean) {
  196. if ($subName !== null) {
  197. $curVal = json_decode('{'.$matches[2].'}', true);
  198. unset($curVal[$name][$subName]);
  199. $childrenClean = substr($that->format($curVal, 0), 1, -1);
  200. }
  201. return $matches[1] . $childrenClean . $matches[3];
  202. }, $this->contents);
  203. return true;
  204. }
  205. public function addMainKey($key, $content)
  206. {
  207. $content = $this->format($content);
  208. // key exists already
  209. $regex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
  210. '('.preg_quote(JsonFile::encode($key)).'\s*:\s*'.self::$JSON_VALUE.')(.*)}s';
  211. if (preg_match($regex, $this->contents, $matches)) {
  212. // invalid match due to un-regexable content, abort
  213. if (!json_decode('{'.$matches[2].'}')) {
  214. return false;
  215. }
  216. $this->contents = $matches[1] . JsonFile::encode($key).': '.$content . $matches[3];
  217. return true;
  218. }
  219. // append at the end of the file and keep whitespace
  220. if (preg_match('#[^{\s](\s*)\}$#', $this->contents, $match)) {
  221. $this->contents = preg_replace(
  222. '#'.$match[1].'\}$#',
  223. addcslashes(',' . $this->newline . $this->indent . JsonFile::encode($key). ': '. $content . $this->newline . '}', '\\'),
  224. $this->contents
  225. );
  226. return true;
  227. }
  228. // append at the end of the file
  229. $this->contents = preg_replace(
  230. '#\}$#',
  231. addcslashes($this->indent . JsonFile::encode($key). ': '.$content . $this->newline . '}', '\\'),
  232. $this->contents
  233. );
  234. return true;
  235. }
  236. public function format($data, $depth = 0)
  237. {
  238. if (is_array($data)) {
  239. reset($data);
  240. if (is_numeric(key($data))) {
  241. foreach ($data as $key => $val) {
  242. $data[$key] = $this->format($val, $depth + 1);
  243. }
  244. return '['.implode(', ', $data).']';
  245. }
  246. $out = '{' . $this->newline;
  247. $elems = array();
  248. foreach ($data as $key => $val) {
  249. $elems[] = str_repeat($this->indent, $depth + 2) . JsonFile::encode($key). ': '.$this->format($val, $depth + 1);
  250. }
  251. return $out . implode(','.$this->newline, $elems) . $this->newline . str_repeat($this->indent, $depth + 1) . '}';
  252. }
  253. return JsonFile::encode($data);
  254. }
  255. protected function detectIndenting()
  256. {
  257. if (preg_match('{^(\s+)"}m', $this->contents, $match)) {
  258. $this->indent = $match[1];
  259. } else {
  260. $this->indent = ' ';
  261. }
  262. }
  263. }