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