OutputFormatter.php 7.9 KB

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