OutputFormatter.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 $decorated;
  21. private $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 "<" special char in given text.
  32. *
  33. * @param string $text Text to escape
  34. *
  35. * @return string Escaped text
  36. */
  37. public static function escape($text)
  38. {
  39. $text = preg_replace('/([^\\\\]?)</', '$1\\<', $text);
  40. return self::escapeTrailingBackslash($text);
  41. }
  42. /**
  43. * Escapes trailing "\" in given text.
  44. *
  45. * @internal
  46. */
  47. public static function escapeTrailingBackslash(string $text): string
  48. {
  49. if (str_ends_with($text, '\\')) {
  50. $len = \strlen($text);
  51. $text = rtrim($text, '\\');
  52. $text = str_replace("\0", '', $text);
  53. $text .= str_repeat("\0", $len - \strlen($text));
  54. }
  55. return $text;
  56. }
  57. /**
  58. * Initializes console output formatter.
  59. *
  60. * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
  61. */
  62. public function __construct(bool $decorated = false, array $styles = [])
  63. {
  64. $this->decorated = $decorated;
  65. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  66. $this->setStyle('info', new OutputFormatterStyle('green'));
  67. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  68. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  69. foreach ($styles as $name => $style) {
  70. $this->setStyle($name, $style);
  71. }
  72. $this->styleStack = new OutputFormatterStyleStack();
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function setDecorated($decorated)
  78. {
  79. $this->decorated = (bool) $decorated;
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function isDecorated()
  85. {
  86. return $this->decorated;
  87. }
  88. /**
  89. * {@inheritdoc}
  90. */
  91. public function setStyle($name, OutputFormatterStyleInterface $style)
  92. {
  93. $this->styles[strtolower($name)] = $style;
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function hasStyle($name)
  99. {
  100. return isset($this->styles[strtolower($name)]);
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function getStyle($name)
  106. {
  107. if (!$this->hasStyle($name)) {
  108. throw new InvalidArgumentException(sprintf('Undefined style: "%s".', $name));
  109. }
  110. return $this->styles[strtolower($name)];
  111. }
  112. /**
  113. * {@inheritdoc}
  114. */
  115. public function format($message)
  116. {
  117. return $this->formatAndWrap((string) $message, 0);
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function formatAndWrap(string $message, int $width)
  123. {
  124. $offset = 0;
  125. $output = '';
  126. $tagRegex = '[a-z][^<>]*+';
  127. $currentLineLength = 0;
  128. preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#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. if (str_contains($output, "\0")) {
  157. return strtr($output, ["\0" => '\\', '\\<' => '<']);
  158. }
  159. return str_replace('\\<', '<', $output);
  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. $style->setHref($match[1]);
  189. } elseif ('options' === $match[0]) {
  190. preg_match_all('([^,;]+)', strtolower($match[1]), $options);
  191. $options = array_shift($options);
  192. foreach ($options as $option) {
  193. $style->setOption($option);
  194. }
  195. } else {
  196. return null;
  197. }
  198. }
  199. return $style;
  200. }
  201. /**
  202. * Applies current style from stack to text, if must be applied.
  203. */
  204. private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string
  205. {
  206. if ('' === $text) {
  207. return '';
  208. }
  209. if (!$width) {
  210. return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text;
  211. }
  212. if (!$currentLineLength && '' !== $current) {
  213. $text = ltrim($text);
  214. }
  215. if ($currentLineLength) {
  216. $prefix = substr($text, 0, $i = $width - $currentLineLength)."\n";
  217. $text = substr($text, $i);
  218. } else {
  219. $prefix = '';
  220. }
  221. preg_match('~(\\n)$~', $text, $matches);
  222. $text = $prefix.preg_replace('~([^\\n]{'.$width.'})\\ *~', "\$1\n", $text);
  223. $text = rtrim($text, "\n").($matches[1] ?? '');
  224. if (!$currentLineLength && '' !== $current && "\n" !== substr($current, -1)) {
  225. $text = "\n".$text;
  226. }
  227. $lines = explode("\n", $text);
  228. foreach ($lines as $line) {
  229. $currentLineLength += \strlen($line);
  230. if ($width <= $currentLineLength) {
  231. $currentLineLength = 0;
  232. }
  233. }
  234. if ($this->isDecorated()) {
  235. foreach ($lines as $i => $line) {
  236. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  237. }
  238. }
  239. return implode("\n", $lines);
  240. }
  241. }