OutputFormatter.php 7.7 KB

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