OutputFormatter.php 7.6 KB

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