OutputFormatter.php 7.6 KB

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