説明なし

OutputFormatter.php 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 "<" and ">" special chars 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\\\\$2', $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. $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
  127. $closeTagRegex = '[a-z][^<>]*+';
  128. $currentLineLength = 0;
  129. preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
  130. foreach ($matches[0] as $i => $match) {
  131. $pos = $match[1];
  132. $text = $match[0];
  133. if (0 != $pos && '\\' == $message[$pos - 1]) {
  134. continue;
  135. }
  136. // add the text up to the next tag
  137. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
  138. $offset = $pos + \strlen($text);
  139. // opening tag?
  140. if ($open = '/' != $text[1]) {
  141. $tag = $matches[1][$i][0];
  142. } else {
  143. $tag = $matches[3][$i][0] ?? '';
  144. }
  145. if (!$open && !$tag) {
  146. // </>
  147. $this->styleStack->pop();
  148. } elseif (null === $style = $this->createStyleFromString($tag)) {
  149. $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength);
  150. } elseif ($open) {
  151. $this->styleStack->push($style);
  152. } else {
  153. $this->styleStack->pop($style);
  154. }
  155. }
  156. $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
  157. return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']);
  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. $url = preg_replace('{\\\\([<>])}', '$1', $match[1]);
  187. $style->setHref($url);
  188. } elseif ('options' === $match[0]) {
  189. preg_match_all('([^,;]+)', strtolower($match[1]), $options);
  190. $options = array_shift($options);
  191. foreach ($options as $option) {
  192. $style->setOption($option);
  193. }
  194. } else {
  195. return null;
  196. }
  197. }
  198. return $style;
  199. }
  200. /**
  201. * Applies current style from stack to text, if must be applied.
  202. */
  203. private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string
  204. {
  205. if ('' === $text) {
  206. return '';
  207. }
  208. if (!$width) {
  209. return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text;
  210. }
  211. if (!$currentLineLength && '' !== $current) {
  212. $text = ltrim($text);
  213. }
  214. if ($currentLineLength) {
  215. $prefix = substr($text, 0, $i = $width - $currentLineLength)."\n";
  216. $text = substr($text, $i);
  217. } else {
  218. $prefix = '';
  219. }
  220. preg_match('~(\\n)$~', $text, $matches);
  221. $text = $prefix.preg_replace('~([^\\n]{'.$width.'})\\ *~', "\$1\n", $text);
  222. $text = rtrim($text, "\n").($matches[1] ?? '');
  223. if (!$currentLineLength && '' !== $current && "\n" !== substr($current, -1)) {
  224. $text = "\n".$text;
  225. }
  226. $lines = explode("\n", $text);
  227. foreach ($lines as $line) {
  228. $currentLineLength += \strlen($line);
  229. if ($width <= $currentLineLength) {
  230. $currentLineLength = 0;
  231. }
  232. }
  233. if ($this->isDecorated()) {
  234. foreach ($lines as $i => $line) {
  235. $lines[$i] = $this->styleStack->getCurrent()->apply($line);
  236. }
  237. }
  238. return implode("\n", $lines);
  239. }
  240. }