OutputFormatter.php 9.1 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 array $styles = [];
  23. private OutputFormatterStyleStack $styleStack;
  24. public function __clone()
  25. {
  26. $this->styleStack = clone $this->styleStack;
  27. foreach ($this->styles as $key => $value) {
  28. $this->styles[$key] = clone $value;
  29. }
  30. }
  31. /**
  32. * Escapes "<" and ">" special chars in given text.
  33. */
  34. public static function escape(string $text): string
  35. {
  36. $text = preg_replace('/([^\\\\]|^)([<>])/', '$1\\\\$2', $text);
  37. return self::escapeTrailingBackslash($text);
  38. }
  39. /**
  40. * Escapes trailing "\" in given text.
  41. *
  42. * @internal
  43. */
  44. public static function escapeTrailingBackslash(string $text): string
  45. {
  46. if (str_ends_with($text, '\\')) {
  47. $len = \strlen($text);
  48. $text = rtrim($text, '\\');
  49. $text = str_replace("\0", '', $text);
  50. $text .= str_repeat("\0", $len - \strlen($text));
  51. }
  52. return $text;
  53. }
  54. /**
  55. * Initializes console output formatter.
  56. *
  57. * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
  58. */
  59. public function __construct(
  60. private bool $decorated = false,
  61. array $styles = [],
  62. ) {
  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. public function setDecorated(bool $decorated): void
  73. {
  74. $this->decorated = $decorated;
  75. }
  76. public function isDecorated(): bool
  77. {
  78. return $this->decorated;
  79. }
  80. public function setStyle(string $name, OutputFormatterStyleInterface $style): void
  81. {
  82. $this->styles[strtolower($name)] = $style;
  83. }
  84. public function hasStyle(string $name): bool
  85. {
  86. return isset($this->styles[strtolower($name)]);
  87. }
  88. public function getStyle(string $name): OutputFormatterStyleInterface
  89. {
  90. if (!$this->hasStyle($name)) {
  91. throw new InvalidArgumentException(\sprintf('Undefined style: "%s".', $name));
  92. }
  93. return $this->styles[strtolower($name)];
  94. }
  95. public function format(?string $message): ?string
  96. {
  97. return $this->formatAndWrap($message, 0);
  98. }
  99. public function formatAndWrap(?string $message, int $width): string
  100. {
  101. if (null === $message) {
  102. return '';
  103. }
  104. // For ASCII-only strings, byte positions equal character positions,
  105. // so we can use native strlen/substr which is much faster than Helper::length/substr.
  106. $isAscii = !preg_match('/[\x80-\xFF]/', $message);
  107. $offset = 0;
  108. $output = '';
  109. $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
  110. $closeTagRegex = '[a-z][^<>]*+';
  111. $currentLineLength = 0;
  112. preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
  113. foreach ($matches[0] as $i => $match) {
  114. $pos = $match[1];
  115. $text = $match[0];
  116. if (0 != $pos && '\\' == $message[$pos - 1]) {
  117. continue;
  118. }
  119. if ($isAscii) {
  120. // For ASCII, byte position = character position, no conversion needed
  121. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  122. $offset = $pos + \strlen($text);
  123. } else {
  124. // convert byte position to character position.
  125. $pos = Helper::length(substr($message, 0, $pos));
  126. // add the text up to the next tag
  127. $output .= $this->applyCurrentStyle(Helper::substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  128. $offset = $pos + Helper::length($text);
  129. }
  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($isAscii ? substr($message, $offset) : 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)->toUnicodeString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding);
  240. }
  241. }