OutputFormatter.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 function Symfony\Component\String\b;
  13. /**
  14. * Formatter class for console output.
  15. *
  16. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  17. * @author Roland Franssen <franssen.roland@gmail.com>
  18. */
  19. class OutputFormatter implements WrappableOutputFormatterInterface
  20. {
  21. private bool $decorated;
  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(bool $decorated = false, array $styles = [])
  60. {
  61. $this->decorated = $decorated;
  62. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  63. $this->setStyle('info', new OutputFormatterStyle('green'));
  64. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  65. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  66. foreach ($styles as $name => $style) {
  67. $this->setStyle($name, $style);
  68. }
  69. $this->styleStack = new OutputFormatterStyleStack();
  70. }
  71. /**
  72. * @return void
  73. */
  74. public function setDecorated(bool $decorated)
  75. {
  76. $this->decorated = $decorated;
  77. }
  78. public function isDecorated(): bool
  79. {
  80. return $this->decorated;
  81. }
  82. /**
  83. * @return void
  84. */
  85. public function setStyle(string $name, OutputFormatterStyleInterface $style)
  86. {
  87. $this->styles[strtolower($name)] = $style;
  88. }
  89. public function hasStyle(string $name): bool
  90. {
  91. return isset($this->styles[strtolower($name)]);
  92. }
  93. public function getStyle(string $name): OutputFormatterStyleInterface
  94. {
  95. if (!$this->hasStyle($name)) {
  96. throw new InvalidArgumentException(sprintf('Undefined style: "%s".', $name));
  97. }
  98. return $this->styles[strtolower($name)];
  99. }
  100. public function format(?string $message): ?string
  101. {
  102. return $this->formatAndWrap($message, 0);
  103. }
  104. /**
  105. * @return string
  106. */
  107. public function formatAndWrap(?string $message, int $width)
  108. {
  109. if (null === $message) {
  110. return '';
  111. }
  112. $offset = 0;
  113. $output = '';
  114. $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
  115. $closeTagRegex = '[a-z][^<>]*+';
  116. $currentLineLength = 0;
  117. preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
  118. foreach ($matches[0] as $i => $match) {
  119. $pos = $match[1];
  120. $text = $match[0];
  121. if (0 != $pos && '\\' == $message[$pos - 1]) {
  122. continue;
  123. }
  124. // add the text up to the next tag
  125. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  126. $offset = $pos + \strlen($text);
  127. // opening tag?
  128. if ($open = '/' !== $text[1]) {
  129. $tag = $matches[1][$i][0];
  130. } else {
  131. $tag = $matches[3][$i][0] ?? '';
  132. }
  133. if (!$open && !$tag) {
  134. // </>
  135. $this->styleStack->pop();
  136. } elseif (null === $style = $this->createStyleFromString($tag)) {
  137. $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength);
  138. } elseif ($open) {
  139. $this->styleStack->push($style);
  140. } else {
  141. $this->styleStack->pop($style);
  142. }
  143. }
  144. $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
  145. return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']);
  146. }
  147. public function getStyleStack(): OutputFormatterStyleStack
  148. {
  149. return $this->styleStack;
  150. }
  151. /**
  152. * Tries to create new style instance from string.
  153. */
  154. private function createStyleFromString(string $string): ?OutputFormatterStyleInterface
  155. {
  156. if (isset($this->styles[$string])) {
  157. return $this->styles[$string];
  158. }
  159. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
  160. return null;
  161. }
  162. $style = new OutputFormatterStyle();
  163. foreach ($matches as $match) {
  164. array_shift($match);
  165. $match[0] = strtolower($match[0]);
  166. if ('fg' == $match[0]) {
  167. $style->setForeground(strtolower($match[1]));
  168. } elseif ('bg' == $match[0]) {
  169. $style->setBackground(strtolower($match[1]));
  170. } elseif ('href' === $match[0]) {
  171. $url = preg_replace('{\\\\([<>])}', '$1', $match[1]);
  172. $style->setHref($url);
  173. } elseif ('options' === $match[0]) {
  174. preg_match_all('([^,;]+)', strtolower($match[1]), $options);
  175. $options = array_shift($options);
  176. foreach ($options as $option) {
  177. $style->setOption($option);
  178. }
  179. } else {
  180. return null;
  181. }
  182. }
  183. return $style;
  184. }
  185. /**
  186. * Applies current style from stack to text, if must be applied.
  187. */
  188. private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string
  189. {
  190. if ('' === $text) {
  191. return '';
  192. }
  193. if (!$width) {
  194. return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text;
  195. }
  196. if (!$currentLineLength && '' !== $current) {
  197. $text = ltrim($text);
  198. }
  199. if ($currentLineLength) {
  200. $prefix = substr($text, 0, $i = $width - $currentLineLength)."\n";
  201. $text = substr($text, $i);
  202. } else {
  203. $prefix = '';
  204. }
  205. preg_match('~(\\n)$~', $text, $matches);
  206. $text = $prefix.$this->addLineBreaks($text, $width);
  207. $text = rtrim($text, "\n").($matches[1] ?? '');
  208. if (!$currentLineLength && '' !== $current && !str_ends_with($current, "\n")) {
  209. $text = "\n".$text;
  210. }
  211. $lines = explode("\n", $text);
  212. foreach ($lines as $line) {
  213. $currentLineLength += \strlen($line);
  214. if ($width <= $currentLineLength) {
  215. $currentLineLength = 0;
  216. }
  217. }
  218. if ($this->isDecorated()) {
  219. foreach ($lines as $i => $line) {
  220. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  221. }
  222. }
  223. return implode("\n", $lines);
  224. }
  225. private function addLineBreaks(string $text, int $width): string
  226. {
  227. $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8';
  228. return b($text)->toCodePointString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding);
  229. }
  230. }