OutputFormatter.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 $decorated;
  22. private $styles = [];
  23. private $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. * @return string
  35. */
  36. public static function escape(string $text)
  37. {
  38. $text = preg_replace('/([^\\\\]|^)([<>])/', '$1\\\\$2', $text);
  39. return self::escapeTrailingBackslash($text);
  40. }
  41. /**
  42. * Escapes trailing "\" in given text.
  43. *
  44. * @internal
  45. */
  46. public static function escapeTrailingBackslash(string $text): string
  47. {
  48. if (str_ends_with($text, '\\')) {
  49. $len = \strlen($text);
  50. $text = rtrim($text, '\\');
  51. $text = str_replace("\0", '', $text);
  52. $text .= str_repeat("\0", $len - \strlen($text));
  53. }
  54. return $text;
  55. }
  56. /**
  57. * Initializes console output formatter.
  58. *
  59. * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
  60. */
  61. public function __construct(bool $decorated = false, array $styles = [])
  62. {
  63. $this->decorated = $decorated;
  64. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  65. $this->setStyle('info', new OutputFormatterStyle('green'));
  66. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  67. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  68. foreach ($styles as $name => $style) {
  69. $this->setStyle($name, $style);
  70. }
  71. $this->styleStack = new OutputFormatterStyleStack();
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function setDecorated(bool $decorated)
  77. {
  78. $this->decorated = $decorated;
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public function isDecorated()
  84. {
  85. return $this->decorated;
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function setStyle(string $name, OutputFormatterStyleInterface $style)
  91. {
  92. $this->styles[strtolower($name)] = $style;
  93. }
  94. /**
  95. * {@inheritdoc}
  96. */
  97. public function hasStyle(string $name)
  98. {
  99. return isset($this->styles[strtolower($name)]);
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function getStyle(string $name)
  105. {
  106. if (!$this->hasStyle($name)) {
  107. throw new InvalidArgumentException(sprintf('Undefined style: "%s".', $name));
  108. }
  109. return $this->styles[strtolower($name)];
  110. }
  111. /**
  112. * {@inheritdoc}
  113. */
  114. public function format(?string $message)
  115. {
  116. return $this->formatAndWrap($message, 0);
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function formatAndWrap(?string $message, int $width)
  122. {
  123. if (null === $message) {
  124. return '';
  125. }
  126. $offset = 0;
  127. $output = '';
  128. $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
  129. $closeTagRegex = '[a-z][^<>]*+';
  130. $currentLineLength = 0;
  131. preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
  132. foreach ($matches[0] as $i => $match) {
  133. $pos = $match[1];
  134. $text = $match[0];
  135. if (0 != $pos && '\\' == $message[$pos - 1]) {
  136. continue;
  137. }
  138. // add the text up to the next tag
  139. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  140. $offset = $pos + \strlen($text);
  141. // opening tag?
  142. if ($open = '/' != $text[1]) {
  143. $tag = $matches[1][$i][0];
  144. } else {
  145. $tag = $matches[3][$i][0] ?? '';
  146. }
  147. if (!$open && !$tag) {
  148. // </>
  149. $this->styleStack->pop();
  150. } elseif (null === $style = $this->createStyleFromString($tag)) {
  151. $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength);
  152. } elseif ($open) {
  153. $this->styleStack->push($style);
  154. } else {
  155. $this->styleStack->pop($style);
  156. }
  157. }
  158. $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
  159. return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']);
  160. }
  161. /**
  162. * @return OutputFormatterStyleStack
  163. */
  164. public function getStyleStack()
  165. {
  166. return $this->styleStack;
  167. }
  168. /**
  169. * Tries to create new style instance from string.
  170. */
  171. private function createStyleFromString(string $string): ?OutputFormatterStyleInterface
  172. {
  173. if (isset($this->styles[$string])) {
  174. return $this->styles[$string];
  175. }
  176. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
  177. return null;
  178. }
  179. $style = new OutputFormatterStyle();
  180. foreach ($matches as $match) {
  181. array_shift($match);
  182. $match[0] = strtolower($match[0]);
  183. if ('fg' == $match[0]) {
  184. $style->setForeground(strtolower($match[1]));
  185. } elseif ('bg' == $match[0]) {
  186. $style->setBackground(strtolower($match[1]));
  187. } elseif ('href' === $match[0]) {
  188. $url = preg_replace('{\\\\([<>])}', '$1', $match[1]);
  189. $style->setHref($url);
  190. } elseif ('options' === $match[0]) {
  191. preg_match_all('([^,;]+)', strtolower($match[1]), $options);
  192. $options = array_shift($options);
  193. foreach ($options as $option) {
  194. $style->setOption($option);
  195. }
  196. } else {
  197. return null;
  198. }
  199. }
  200. return $style;
  201. }
  202. /**
  203. * Applies current style from stack to text, if must be applied.
  204. */
  205. private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string
  206. {
  207. if ('' === $text) {
  208. return '';
  209. }
  210. if (!$width) {
  211. return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text;
  212. }
  213. if (!$currentLineLength && '' !== $current) {
  214. $text = ltrim($text);
  215. }
  216. if ($currentLineLength) {
  217. $prefix = substr($text, 0, $i = $width - $currentLineLength)."\n";
  218. $text = substr($text, $i);
  219. } else {
  220. $prefix = '';
  221. }
  222. preg_match('~(\\n)$~', $text, $matches);
  223. $text = $prefix.$this->addLineBreaks($text, $width);
  224. $text = rtrim($text, "\n").($matches[1] ?? '');
  225. if (!$currentLineLength && '' !== $current && "\n" !== substr($current, -1)) {
  226. $text = "\n".$text;
  227. }
  228. $lines = explode("\n", $text);
  229. foreach ($lines as $line) {
  230. $currentLineLength += \strlen($line);
  231. if ($width <= $currentLineLength) {
  232. $currentLineLength = 0;
  233. }
  234. }
  235. if ($this->isDecorated()) {
  236. foreach ($lines as $i => $line) {
  237. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  238. }
  239. }
  240. return implode("\n", $lines);
  241. }
  242. private function addLineBreaks(string $text, int $width): string
  243. {
  244. $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8';
  245. return b($text)->toCodePointString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding);
  246. }
  247. }