OutputFormatter.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. * @return string Escaped text
  34. */
  35. public static function escape(string $text)
  36. {
  37. $text = preg_replace('/([^\\\\]?)</', '$1\\<', $text);
  38. return self::escapeTrailingBackslash($text);
  39. }
  40. /**
  41. * Escapes trailing "\" in given text.
  42. *
  43. * @internal
  44. */
  45. public static function escapeTrailingBackslash(string $text): string
  46. {
  47. if ('\\' === substr($text, -1)) {
  48. $len = \strlen($text);
  49. $text = rtrim($text, '\\');
  50. $text = str_replace("\0", '', $text);
  51. $text .= str_repeat("\0", $len - \strlen($text));
  52. }
  53. return $text;
  54. }
  55. /**
  56. * Initializes console output formatter.
  57. *
  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(bool $decorated)
  76. {
  77. $this->decorated = $decorated;
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function isDecorated()
  83. {
  84. return $this->decorated;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. public function setStyle(string $name, OutputFormatterStyleInterface $style)
  90. {
  91. $this->styles[strtolower($name)] = $style;
  92. }
  93. /**
  94. * {@inheritdoc}
  95. */
  96. public function hasStyle(string $name)
  97. {
  98. return isset($this->styles[strtolower($name)]);
  99. }
  100. /**
  101. * {@inheritdoc}
  102. */
  103. public function getStyle(string $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(?string $message)
  114. {
  115. return $this->formatAndWrap($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][^<>]*+';
  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 = $matches[3][$i][0] ?? '';
  141. }
  142. if (!$open && !$tag) {
  143. // </>
  144. $this->styleStack->pop();
  145. } elseif (null === $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. private function createStyleFromString(string $string): ?OutputFormatterStyleInterface
  170. {
  171. if (isset($this->styles[$string])) {
  172. return $this->styles[$string];
  173. }
  174. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
  175. return null;
  176. }
  177. $style = new OutputFormatterStyle();
  178. foreach ($matches as $match) {
  179. array_shift($match);
  180. $match[0] = strtolower($match[0]);
  181. if ('fg' == $match[0]) {
  182. $style->setForeground(strtolower($match[1]));
  183. } elseif ('bg' == $match[0]) {
  184. $style->setBackground(strtolower($match[1]));
  185. } elseif ('href' === $match[0]) {
  186. $style->setHref($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 null;
  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. foreach ($lines as $line) {
  227. $currentLineLength += \strlen($line);
  228. if ($width <= $currentLineLength) {
  229. $currentLineLength = 0;
  230. }
  231. }
  232. if ($this->isDecorated()) {
  233. foreach ($lines as $i => $line) {
  234. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  235. }
  236. }
  237. return implode("\n", $lines);
  238. }
  239. }