OutputFormatter.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. $offset = 0;
  105. $output = '';
  106. $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
  107. $closeTagRegex = '[a-z][^<>]*+';
  108. $currentLineLength = 0;
  109. preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
  110. foreach ($matches[0] as $i => $match) {
  111. $pos = $match[1];
  112. $text = $match[0];
  113. if (0 != $pos && '\\' == $message[$pos - 1]) {
  114. continue;
  115. }
  116. // convert byte position to character position.
  117. $pos = Helper::length(substr($message, 0, $pos));
  118. // add the text up to the next tag
  119. $output .= $this->applyCurrentStyle(Helper::substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  120. $offset = $pos + Helper::length($text);
  121. // opening tag?
  122. if ($open = '/' !== $text[1]) {
  123. $tag = $matches[1][$i][0];
  124. } else {
  125. $tag = $matches[3][$i][0] ?? '';
  126. }
  127. if (!$open && !$tag) {
  128. // </>
  129. $this->styleStack->pop();
  130. } elseif (null === $style = $this->createStyleFromString($tag)) {
  131. $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength);
  132. } elseif ($open) {
  133. $this->styleStack->push($style);
  134. } else {
  135. $this->styleStack->pop($style);
  136. }
  137. }
  138. $output .= $this->applyCurrentStyle(Helper::substr($message, $offset), $output, $width, $currentLineLength);
  139. return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']);
  140. }
  141. public function getStyleStack(): OutputFormatterStyleStack
  142. {
  143. return $this->styleStack;
  144. }
  145. /**
  146. * Tries to create new style instance from string.
  147. */
  148. private function createStyleFromString(string $string): ?OutputFormatterStyleInterface
  149. {
  150. if (isset($this->styles[$string])) {
  151. return $this->styles[$string];
  152. }
  153. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
  154. return null;
  155. }
  156. $style = new OutputFormatterStyle();
  157. foreach ($matches as $match) {
  158. array_shift($match);
  159. $match[0] = strtolower($match[0]);
  160. if ('fg' == $match[0]) {
  161. $style->setForeground(strtolower($match[1]));
  162. } elseif ('bg' == $match[0]) {
  163. $style->setBackground(strtolower($match[1]));
  164. } elseif ('href' === $match[0]) {
  165. $url = preg_replace('{\\\\([<>])}', '$1', $match[1]);
  166. $style->setHref($url);
  167. } elseif ('options' === $match[0]) {
  168. preg_match_all('([^,;]+)', strtolower($match[1]), $options);
  169. $options = array_shift($options);
  170. foreach ($options as $option) {
  171. $style->setOption($option);
  172. }
  173. } else {
  174. return null;
  175. }
  176. }
  177. return $style;
  178. }
  179. /**
  180. * Applies current style from stack to text, if must be applied.
  181. */
  182. private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string
  183. {
  184. if ('' === $text) {
  185. return '';
  186. }
  187. if (!$width) {
  188. return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text;
  189. }
  190. if (!$currentLineLength && '' !== $current) {
  191. $text = ltrim($text);
  192. }
  193. if ($currentLineLength) {
  194. $lines = explode("\n", $text, 2);
  195. $prefix = Helper::substr($lines[0], 0, $i = $width - $currentLineLength)."\n";
  196. $text = Helper::substr($lines[0], $i);
  197. if (isset($lines[1])) {
  198. // $prefix may contain the full first line in which the \n is already a part of $prefix.
  199. if ('' !== $text) {
  200. $text .= "\n";
  201. }
  202. $text .= $lines[1];
  203. }
  204. } else {
  205. $prefix = '';
  206. }
  207. preg_match('~(\\n)$~', $text, $matches);
  208. $text = $prefix.$this->addLineBreaks($text, $width);
  209. $text = rtrim($text, "\n").($matches[1] ?? '');
  210. if (!$currentLineLength && '' !== $current && !str_ends_with($current, "\n")) {
  211. $text = "\n".$text;
  212. }
  213. $lines = explode("\n", $text);
  214. foreach ($lines as $i => $line) {
  215. $currentLineLength = 0 === $i ? $currentLineLength + Helper::length($line) : Helper::length($line);
  216. if ($width <= $currentLineLength) {
  217. $currentLineLength = 0;
  218. }
  219. }
  220. if ($this->isDecorated()) {
  221. foreach ($lines as $i => $line) {
  222. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  223. }
  224. }
  225. return implode("\n", $lines);
  226. }
  227. private function addLineBreaks(string $text, int $width): string
  228. {
  229. $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8';
  230. return b($text)->toUnicodeString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding);
  231. }
  232. }