JsonManipulator.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 $contents;
  19. private $newline;
  20. private $indent;
  21. public function __construct($contents)
  22. {
  23. $contents = trim($contents);
  24. if (!preg_match('#^\{(.*)\}$#s', $contents)) {
  25. throw new \InvalidArgumentException('The json file must be an object ({})');
  26. }
  27. $this->newline = false !== strpos("\r\n", $contents) ? "\r\n": "\n";
  28. $this->contents = $contents;
  29. $this->detectIndenting();
  30. }
  31. public function getContents()
  32. {
  33. return $this->contents . $this->newline;
  34. }
  35. public function addLink($type, $package, $constraint)
  36. {
  37. // no link of that type yet
  38. if (!preg_match('#"'.$type.'":\s*\{#', $this->contents)) {
  39. $this->addMainKey($type, $this->format(array($package => $constraint)));
  40. return true;
  41. }
  42. $linksRegex = '#("'.$type.'":\s*\{)([^}]+)(\})#s';
  43. if (!preg_match($linksRegex, $this->contents, $match)) {
  44. return false;
  45. }
  46. $links = $match[2];
  47. $packageRegex = str_replace('/', '\\\\?/', preg_quote($package));
  48. // link exists already
  49. if (preg_match('{"'.$packageRegex.'"\s*:}i', $links)) {
  50. $links = preg_replace('{"'.$packageRegex.'"(\s*:\s*)"[^"]+"}i', JsonFile::encode($package).'${1}"'.$constraint.'"', $links);
  51. } elseif (preg_match('#[^\s](\s*)$#', $links, $match)) {
  52. // link missing but non empty links
  53. $links = preg_replace(
  54. '#'.$match[1].'$#',
  55. ',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $match[1],
  56. $links
  57. );
  58. } else {
  59. // links empty
  60. $links = $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $links;
  61. }
  62. $this->contents = preg_replace($linksRegex, '${1}'.$links.'$3', $this->contents);
  63. return true;
  64. }
  65. public function addRepository($name, $config)
  66. {
  67. return $this->addSubNode('repositories', $name, $config);
  68. }
  69. public function removeRepository($name)
  70. {
  71. return $this->removeSubNode('repositories', $name);
  72. }
  73. public function addConfigSetting($name, $value)
  74. {
  75. return $this->addSubNode('config', $name, $value);
  76. }
  77. public function removeConfigSetting($name)
  78. {
  79. return $this->removeSubNode('config', $name);
  80. }
  81. public function addSubNode($mainNode, $name, $value)
  82. {
  83. // no main node yet
  84. if (!preg_match('#"'.$mainNode.'":\s*\{#', $this->contents)) {
  85. $this->addMainKey(''.$mainNode.'', $this->format(array($name => $value)));
  86. return true;
  87. }
  88. // main node content not match-able
  89. $nodeRegex = '#("'.$mainNode.'":\s*\{)('.self::$RECURSE_BLOCKS.')(\})#s';
  90. if (!preg_match($nodeRegex, $this->contents, $match)) {
  91. return false;
  92. }
  93. $children = $match[2];
  94. // invalid match due to un-regexable content, abort
  95. if (!json_decode('{'.$children.'}')) {
  96. return false;
  97. }
  98. // child exists
  99. if (preg_match('{("'.preg_quote($name).'"\s*:\s*)([0-9.]+|null|true|false|"[^"]+"|\{'.self::$RECURSE_BLOCKS.'\})(,?)}', $children, $matches)) {
  100. $children = preg_replace('{("'.preg_quote($name).'"\s*:\s*)([0-9.]+|null|true|false|"[^"]+"|\{'.self::$RECURSE_BLOCKS.'\})(,?)}', '${1}'.$this->format($value, 1).'$3', $children);
  101. } elseif (preg_match('#[^\s](\s*)$#', $children, $match)) {
  102. // child missing but non empty children
  103. $children = preg_replace(
  104. '#'.$match[1].'$#',
  105. ',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $match[1],
  106. $children
  107. );
  108. } else {
  109. // children present but empty
  110. $children = $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $children;
  111. }
  112. $this->contents = preg_replace($nodeRegex, '${1}'.$children.'$3', $this->contents);
  113. return true;
  114. }
  115. public function removeSubNode($mainNode, $name)
  116. {
  117. // no node
  118. if (!preg_match('#"'.$mainNode.'":\s*\{#', $this->contents)) {
  119. return true;
  120. }
  121. // empty node
  122. if (preg_match('#"'.$mainNode.'":\s*\{\s*\}#s', $this->contents)) {
  123. return true;
  124. }
  125. // no node content match-able
  126. $nodeRegex = '#("'.$mainNode.'":\s*\{)('.self::$RECURSE_BLOCKS.')(\})#s';
  127. if (!preg_match($nodeRegex, $this->contents, $match)) {
  128. return false;
  129. }
  130. $children = $match[2];
  131. // invalid match due to un-regexable content, abort
  132. if (!json_decode('{'.$children.'}')) {
  133. return false;
  134. }
  135. if (preg_match('{"'.preg_quote($name).'"\s*:}i', $children)) {
  136. if (preg_match_all('{"'.preg_quote($name).'"\s*:\s*(?:[0-9.]+|null|true|false|"[^"]+"|\{'.self::$RECURSE_BLOCKS.'\})}', $children, $matches)) {
  137. $bestMatch = '';
  138. foreach ($matches[0] as $match) {
  139. if (strlen($bestMatch) < strlen($match)) {
  140. $bestMatch = $match;
  141. }
  142. }
  143. $children = preg_replace('{,\s*'.preg_quote($bestMatch).'}i', '', $children, -1, $count);
  144. if (1 !== $count) {
  145. $children = preg_replace('{'.preg_quote($bestMatch).'\s*,?\s*}i', '', $children, -1, $count);
  146. if (1 !== $count) {
  147. return false;
  148. }
  149. }
  150. }
  151. }
  152. if (!trim($children)) {
  153. $this->contents = preg_replace($nodeRegex, '$1'.$this->newline.$this->indent.'}', $this->contents);
  154. return true;
  155. }
  156. $this->contents = preg_replace($nodeRegex, '${1}'.$children.'$3', $this->contents);
  157. return true;
  158. }
  159. public function addMainKey($key, $content)
  160. {
  161. if (preg_match('#[^{\s](\s*)\}$#', $this->contents, $match)) {
  162. $this->contents = preg_replace(
  163. '#'.$match[1].'\}$#',
  164. ',' . $this->newline . $this->indent . JsonFile::encode($key). ': '. $content . $this->newline . '}',
  165. $this->contents
  166. );
  167. } else {
  168. $this->contents = preg_replace(
  169. '#\}$#',
  170. $this->indent . JsonFile::encode($key). ': '.$content . $this->newline . '}',
  171. $this->contents
  172. );
  173. }
  174. }
  175. protected function format($data, $depth = 0)
  176. {
  177. if (is_array($data)) {
  178. reset($data);
  179. if (is_numeric(key($data))) {
  180. return '['.implode(', ', $data).']';
  181. }
  182. $out = '{' . $this->newline;
  183. foreach ($data as $key => $val) {
  184. $elems[] = str_repeat($this->indent, $depth + 2) . JsonFile::encode($key). ': '.$this->format($val, $depth + 1);
  185. }
  186. return $out . implode(','.$this->newline, $elems) . $this->newline . str_repeat($this->indent, $depth + 1) . '}';
  187. }
  188. return JsonFile::encode($data);
  189. }
  190. protected function detectIndenting()
  191. {
  192. if (preg_match('{^(\s+)"}', $this->contents, $match)) {
  193. $this->indent = $match[1];
  194. } else {
  195. $this->indent = ' ';
  196. }
  197. }
  198. }