OutputFormatter.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Formatter;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Helper\Helper;
  13. use function Symfony\Component\String\b;
  14. /**
  15. * Formatter class for console output.
  16. *
  17. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  18. * @author Roland Franssen <franssen.roland@gmail.com>
  19. */
  20. class OutputFormatter implements WrappableOutputFormatterInterface
  21. {
  22. private bool $decorated;
  23. private array $styles = [];
  24. private OutputFormatterStyleStack $styleStack;
  25. public function __clone()
  26. {
  27. $this->styleStack = clone $this->styleStack;
  28. foreach ($this->styles as $key => $value) {
  29. $this->styles[$key] = clone $value;
  30. }
  31. }
  32. /**
  33. * Escapes "<" and ">" special chars in given text.
  34. */
  35. public static function escape(string $text): string
  36. {
  37. $text = preg_replace('/([^\\\\]|^)([<>])/', '$1\\\\$2', $text);
  38. return self::escapeTrailingBackslash($text);
  39. }
  40. /**
  41. * Escapes trailing "\" in given text.
  42. *
  43. * @internal
  44. */
  45. public static function escapeTrailingBackslash(string $text): string
  46. {
  47. if (str_ends_with($text, '\\')) {
  48. $len = \strlen($text);
  49. $text = rtrim($text, '\\');
  50. $text = str_replace("\0", '', $text);
  51. $text .= str_repeat("\0", $len - \strlen($text));
  52. }
  53. return $text;
  54. }
  55. /**
  56. * Initializes console output formatter.
  57. *
  58. * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
  59. */
  60. public function __construct(bool $decorated = false, array $styles = [])
  61. {
  62. $this->decorated = $decorated;
  63. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  64. $this->setStyle('info', new OutputFormatterStyle('green'));
  65. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  66. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  67. foreach ($styles as $name => $style) {
  68. $this->setStyle($name, $style);
  69. }
  70. $this->styleStack = new OutputFormatterStyleStack();
  71. }
  72. /**
  73. * @return void
  74. */
  75. public function setDecorated(bool $decorated)
  76. {
  77. $this->decorated = $decorated;
  78. }
  79. public function isDecorated(): bool
  80. {
  81. return $this->decorated;
  82. }
  83. /**
  84. * @return void
  85. */
  86. public function setStyle(string $name, OutputFormatterStyleInterface $style)
  87. {
  88. $this->styles[strtolower($name)] = $style;
  89. }
  90. public function hasStyle(string $name): bool
  91. {
  92. return isset($this->styles[strtolower($name)]);
  93. }
  94. public function getStyle(string $name): OutputFormatterStyleInterface
  95. {
  96. if (!$this->hasStyle($name)) {
  97. throw new InvalidArgumentException(\sprintf('Undefined style: "%s".', $name));
  98. }
  99. return $this->styles[strtolower($name)];
  100. }
  101. public function format(?string $message): ?string
  102. {
  103. return $this->formatAndWrap($message, 0);
  104. }
  105. /**
  106. * @return string
  107. */
  108. public function formatAndWrap(?string $message, int $width)
  109. {
  110. if (null === $message) {
  111. return '';
  112. }
  113. $offset = 0;
  114. $output = '';
  115. $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
  116. $closeTagRegex = '[a-z][^<>]*+';
  117. $currentLineLength = 0;
  118. preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
  119. foreach ($matches[0] as $i => $match) {
  120. $pos = $match[1];
  121. $text = $match[0];
  122. if (0 != $pos && '\\' == $message[$pos - 1]) {
  123. continue;
  124. }
  125. // convert byte position to character position.
  126. $pos = Helper::length(substr($message, 0, $pos));
  127. // add the text up to the next tag
  128. $output .= $this->applyCurrentStyle(Helper::substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  129. $offset = $pos + Helper::length($text);
  130. // opening tag?
  131. if ($open = '/' !== $text[1]) {
  132. $tag = $matches[1][$i][0];
  133. } else {
  134. $tag = $matches[3][$i][0] ?? '';
  135. }
  136. if (!$open && !$tag) {
  137. // </>
  138. $this->styleStack->pop();
  139. } elseif (null === $style = $this->createStyleFromString($tag)) {
  140. $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength);
  141. } elseif ($open) {
  142. $this->styleStack->push($style);
  143. } else {
  144. $this->styleStack->pop($style);
  145. }
  146. }
  147. $output .= $this->applyCurrentStyle(Helper::substr($message, $offset), $output, $width, $currentLineLength);
  148. return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']);
  149. }
  150. public function getStyleStack(): OutputFormatterStyleStack
  151. {
  152. return $this->styleStack;
  153. }
  154. /**
  155. * Tries to create new style instance from string.
  156. */
  157. private function createStyleFromString(string $string): ?OutputFormatterStyleInterface
  158. {
  159. if (isset($this->styles[$string])) {
  160. return $this->styles[$string];
  161. }
  162. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
  163. return null;
  164. }
  165. $style = new OutputFormatterStyle();
  166. foreach ($matches as $match) {
  167. array_shift($match);
  168. $match[0] = strtolower($match[0]);
  169. if ('fg' == $match[0]) {
  170. $style->setForeground(strtolower($match[1]));
  171. } elseif ('bg' == $match[0]) {
  172. $style->setBackground(strtolower($match[1]));
  173. } elseif ('href' === $match[0]) {
  174. $url = preg_replace('{\\\\([<>])}', '$1', $match[1]);
  175. $style->setHref($url);
  176. } elseif ('options' === $match[0]) {
  177. preg_match_all('([^,;]+)', strtolower($match[1]), $options);
  178. $options = array_shift($options);
  179. foreach ($options as $option) {
  180. $style->setOption($option);
  181. }
  182. } else {
  183. return null;
  184. }
  185. }
  186. return $style;
  187. }
  188. /**
  189. * Applies current style from stack to text, if must be applied.
  190. */
  191. private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string
  192. {
  193. if ('' === $text) {
  194. return '';
  195. }
  196. if (!$width) {
  197. return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text;
  198. }
  199. if (!$currentLineLength && '' !== $current) {
  200. $text = ltrim($text);
  201. }
  202. if ($currentLineLength) {
  203. $lines = explode("\n", $text, 2);
  204. $prefix = Helper::substr($lines[0], 0, $i = $width - $currentLineLength)."\n";
  205. $text = Helper::substr($lines[0], $i);
  206. if (isset($lines[1])) {
  207. // $prefix may contain the full first line in which the \n is already a part of $prefix.
  208. if ('' !== $text) {
  209. $text .= "\n";
  210. }
  211. $text .= $lines[1];
  212. }
  213. } else {
  214. $prefix = '';
  215. }
  216. preg_match('~(\\n)$~', $text, $matches);
  217. $text = $prefix.$this->addLineBreaks($text, $width);
  218. $text = rtrim($text, "\n").($matches[1] ?? '');
  219. if (!$currentLineLength && '' !== $current && !str_ends_with($current, "\n")) {
  220. $text = "\n".$text;
  221. }
  222. $lines = explode("\n", $text);
  223. foreach ($lines as $i => $line) {
  224. $currentLineLength = 0 === $i ? $currentLineLength + Helper::length($line) : Helper::length($line);
  225. if ($width <= $currentLineLength) {
  226. $currentLineLength = 0;
  227. }
  228. }
  229. if ($this->isDecorated()) {
  230. foreach ($lines as $i => $line) {
  231. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  232. }
  233. }
  234. return implode("\n", $lines);
  235. }
  236. private function addLineBreaks(string $text, int $width): string
  237. {
  238. $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8';
  239. return b($text)->toCodePointString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding);
  240. }
  241. }