YamlUpdater.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. <?php
  2. /**
  3. * @package Grav\Installer
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Installer;
  9. use Grav\Common\Utils;
  10. use Symfony\Component\Yaml\Yaml;
  11. use function assert;
  12. use function count;
  13. use function is_array;
  14. use function strlen;
  15. /**
  16. * Grav YAML updater.
  17. *
  18. * NOTE: This class can be initialized during upgrade from an older version of Grav. Make sure it runs there!
  19. */
  20. final class YamlUpdater
  21. {
  22. /** @var string */
  23. protected $filename;
  24. /** @var string[] */
  25. protected $lines;
  26. /** @var array */
  27. protected $comments;
  28. /** @var array */
  29. protected $items;
  30. /** @var bool */
  31. protected $updated = false;
  32. /** @var self[] */
  33. protected static $instance;
  34. public static function instance(string $filename): self
  35. {
  36. if (!isset(self::$instance[$filename])) {
  37. self::$instance[$filename] = new self($filename);
  38. }
  39. return self::$instance[$filename];
  40. }
  41. /**
  42. * @return bool
  43. */
  44. public function save(): bool
  45. {
  46. if (!$this->updated) {
  47. return false;
  48. }
  49. try {
  50. if (!$this->isHandWritten()) {
  51. $yaml = Yaml::dump($this->items, 5, 2);
  52. } else {
  53. $yaml = implode("\n", $this->lines);
  54. $items = Yaml::parse($yaml);
  55. if ($items !== $this->items) {
  56. throw new \RuntimeException('Failed saving the content');
  57. }
  58. }
  59. file_put_contents($this->filename, $yaml);
  60. } catch (\Exception $e) {
  61. throw new \RuntimeException('Failed to update ' . basename($this->filename) . ': ' . $e->getMessage());
  62. }
  63. return true;
  64. }
  65. /**
  66. * @return bool
  67. */
  68. public function isHandWritten(): bool
  69. {
  70. return !empty($this->comments);
  71. }
  72. /**
  73. * @return array
  74. */
  75. public function getComments(): array
  76. {
  77. $comments = [];
  78. foreach ($this->lines as $i => $line) {
  79. if ($this->isLineEmpty($line)) {
  80. $comments[$i+1] = $line;
  81. } elseif ($comment = $this->getInlineComment($line)) {
  82. $comments[$i+1] = $comment;
  83. }
  84. }
  85. return $comments;
  86. }
  87. /**
  88. * @param string $variable
  89. * @param mixed $value
  90. */
  91. public function define(string $variable, $value): void
  92. {
  93. // If variable has already value, we're good.
  94. if ($this->get($variable) !== null) {
  95. return;
  96. }
  97. // If one of the parents isn't array, we're good, too.
  98. if (!$this->canDefine($variable)) {
  99. return;
  100. }
  101. $this->set($variable, $value);
  102. if (!$this->isHandWritten()) {
  103. return;
  104. }
  105. $parts = explode('.', $variable);
  106. $lineNos = $this->findPath($this->lines, $parts);
  107. $count = count($lineNos);
  108. $last = array_key_last($lineNos);
  109. $value = explode("\n", trim(Yaml::dump([$last => $this->get(implode('.', array_keys($lineNos)))], max(0, 5-$count), 2)));
  110. $currentLine = array_pop($lineNos) ?: 0;
  111. $parentLine = array_pop($lineNos);
  112. if ($parentLine !== null) {
  113. $c = $this->getLineIndentation($this->lines[$parentLine] ?? '');
  114. $n = $this->getLineIndentation($this->lines[$parentLine+1] ?? $this->lines[$parentLine] ?? '');
  115. $indent = $n > $c ? $n : $c + 2;
  116. } else {
  117. $indent = 0;
  118. array_unshift($value, '');
  119. }
  120. $spaces = str_repeat(' ', $indent);
  121. foreach ($value as &$line) {
  122. $line = $spaces . $line;
  123. }
  124. unset($line);
  125. array_splice($this->lines, abs($currentLine)+1, 0, $value);
  126. }
  127. public function undefine(string $variable): void
  128. {
  129. // If variable does not have value, we're good.
  130. if ($this->get($variable) === null) {
  131. return;
  132. }
  133. // If one of the parents isn't array, we're good, too.
  134. if (!$this->canDefine($variable)) {
  135. return;
  136. }
  137. $this->undef($variable);
  138. if (!$this->isHandWritten()) {
  139. return;
  140. }
  141. // TODO: support also removing property from handwritten configuration file.
  142. }
  143. private function __construct(string $filename)
  144. {
  145. $content = is_file($filename) ? (string)file_get_contents($filename) : '';
  146. $content = rtrim(str_replace(["\r\n", "\r"], "\n", $content));
  147. $this->filename = $filename;
  148. $this->lines = explode("\n", $content);
  149. $this->comments = $this->getComments();
  150. $this->items = $content ? Yaml::parse($content) : [];
  151. }
  152. /**
  153. * Return array of offsets for the parent nodes. Negative value means position, but not found.
  154. *
  155. * @param array $lines
  156. * @param array $parts
  157. * @return int[]
  158. */
  159. private function findPath(array $lines, array $parts)
  160. {
  161. $test = true;
  162. $indent = -1;
  163. $current = array_shift($parts);
  164. $j = 1;
  165. $found = [];
  166. $space = '';
  167. foreach ($lines as $i => $line) {
  168. if ($this->isLineEmpty($line)) {
  169. if ($this->isLineComment($line) && $this->getLineIndentation($line) > $indent) {
  170. $j = $i;
  171. }
  172. continue;
  173. }
  174. if ($test === true) {
  175. $test = false;
  176. $spaces = strlen($line) - strlen(ltrim($line, ' '));
  177. if ($spaces <= $indent) {
  178. $found[$current] = -$j;
  179. return $found;
  180. }
  181. $indent = $spaces;
  182. $space = $indent ? str_repeat(' ', $indent) : '';
  183. }
  184. if (0 === \strncmp($line, $space, strlen($space))) {
  185. $pattern = "/^{$space}(['\"]?){$current}\\1\:/";
  186. if (preg_match($pattern, $line)) {
  187. $found[$current] = $i;
  188. $current = array_shift($parts);
  189. if ($current === null) {
  190. return $found;
  191. }
  192. $test = true;
  193. }
  194. } else {
  195. $found[$current] = -$j;
  196. return $found;
  197. }
  198. $j = $i;
  199. }
  200. $found[$current] = -$j;
  201. return $found;
  202. }
  203. /**
  204. * Returns true if the current line is blank or if it is a comment line.
  205. *
  206. * @param string $line Contents of the line
  207. * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
  208. */
  209. private function isLineEmpty(string $line): bool
  210. {
  211. return $this->isLineBlank($line) || $this->isLineComment($line);
  212. }
  213. /**
  214. * Returns true if the current line is blank.
  215. *
  216. * @param string $line Contents of the line
  217. * @return bool Returns true if the current line is blank, false otherwise
  218. */
  219. private function isLineBlank(string $line): bool
  220. {
  221. return '' === trim($line, ' ');
  222. }
  223. /**
  224. * Returns true if the current line is a comment line.
  225. *
  226. * @param string $line Contents of the line
  227. * @return bool Returns true if the current line is a comment line, false otherwise
  228. */
  229. private function isLineComment(string $line): bool
  230. {
  231. //checking explicitly the first char of the trim is faster than loops or strpos
  232. $ltrimmedLine = ltrim($line, ' ');
  233. return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
  234. }
  235. /**
  236. * @param string $line
  237. * @return bool
  238. */
  239. private function isInlineComment(string $line): bool
  240. {
  241. return $this->getInlineComment($line) !== null;
  242. }
  243. /**
  244. * @param string $line
  245. * @return string|null
  246. */
  247. private function getInlineComment(string $line): ?string
  248. {
  249. $pos = strpos($line, ' #');
  250. if (false === $pos) {
  251. return null;
  252. }
  253. $parts = explode(' #', $line);
  254. $part = '';
  255. while ($part .= array_shift($parts)) {
  256. // Remove quoted values.
  257. $part = preg_replace('/(([\'"])[^\2]*\2)/', '', $part);
  258. assert(null !== $part);
  259. $part = preg_split('/[\'"]/', $part, 2);
  260. assert(false !== $part);
  261. if (!isset($part[1])) {
  262. $part = $part[0];
  263. array_unshift($parts, str_repeat(' ', strlen($part) - strlen(trim($part, ' '))));
  264. break;
  265. }
  266. $part = $part[1];
  267. }
  268. return implode(' #', $parts);
  269. }
  270. /**
  271. * Returns the current line indentation.
  272. *
  273. * @param string $line
  274. * @return int The current line indentation
  275. */
  276. private function getLineIndentation(string $line): int
  277. {
  278. return \strlen($line) - \strlen(ltrim($line, ' '));
  279. }
  280. /**
  281. * Get value by using dot notation for nested arrays/objects.
  282. *
  283. * @param string $name Dot separated path to the requested value.
  284. * @param mixed $default Default value (or null).
  285. * @return mixed Value.
  286. */
  287. private function get(string $name, $default = null)
  288. {
  289. $path = explode('.', $name);
  290. $current = $this->items;
  291. foreach ($path as $field) {
  292. if (is_array($current) && isset($current[$field])) {
  293. $current = $current[$field];
  294. } else {
  295. return $default;
  296. }
  297. }
  298. return $current;
  299. }
  300. /**
  301. * Set value by using dot notation for nested arrays/objects.
  302. *
  303. * @param string $name Dot separated path to the requested value.
  304. * @param mixed $value New value.
  305. */
  306. private function set(string $name, $value): void
  307. {
  308. $path = explode('.', $name);
  309. $current = &$this->items;
  310. foreach ($path as $field) {
  311. // Handle arrays and scalars.
  312. if (!is_array($current)) {
  313. $current = [$field => []];
  314. } elseif (!isset($current[$field])) {
  315. $current[$field] = [];
  316. }
  317. $current = &$current[$field];
  318. }
  319. $current = $value;
  320. $this->updated = true;
  321. }
  322. /**
  323. * Unset value by using dot notation for nested arrays/objects.
  324. *
  325. * @param string $name Dot separated path to the requested value.
  326. */
  327. private function undef(string $name): void
  328. {
  329. $path = $name !== '' ? explode('.', $name) : [];
  330. if (!$path) {
  331. return;
  332. }
  333. $var = array_pop($path);
  334. $current = &$this->items;
  335. foreach ($path as $field) {
  336. if (!is_array($current) || !isset($current[$field])) {
  337. return;
  338. }
  339. $current = &$current[$field];
  340. }
  341. unset($current[$var]);
  342. $this->updated = true;
  343. }
  344. /**
  345. * Get value by using dot notation for nested arrays/objects.
  346. *
  347. * @param string $name Dot separated path to the requested value.
  348. * @return bool
  349. */
  350. private function canDefine(string $name): bool
  351. {
  352. $path = explode('.', $name);
  353. $current = $this->items;
  354. foreach ($path as $field) {
  355. if (is_array($current)) {
  356. if (!isset($current[$field])) {
  357. return true;
  358. }
  359. $current = $current[$field];
  360. } else {
  361. return false;
  362. }
  363. }
  364. return true;
  365. }
  366. }