OutputFormatter.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. */
  17. class OutputFormatter implements OutputFormatterInterface
  18. {
  19. private $decorated;
  20. private $styles = array();
  21. private $styleStack;
  22. /**
  23. * Escapes "<" special char in given text.
  24. *
  25. * @param string $text Text to escape
  26. *
  27. * @return string Escaped text
  28. */
  29. public static function escape($text)
  30. {
  31. $text = preg_replace('/([^\\\\]?)</', '$1\\<', $text);
  32. return self::escapeTrailingBackslash($text);
  33. }
  34. /**
  35. * Escapes trailing "\" in given text.
  36. *
  37. * @param string $text Text to escape
  38. *
  39. * @return string Escaped text
  40. *
  41. * @internal
  42. */
  43. public static function escapeTrailingBackslash($text)
  44. {
  45. if ('\\' === substr($text, -1)) {
  46. $len = strlen($text);
  47. $text = rtrim($text, '\\');
  48. $text .= str_repeat('<<', $len - strlen($text));
  49. }
  50. return $text;
  51. }
  52. /**
  53. * Initializes console output formatter.
  54. *
  55. * @param bool $decorated Whether this formatter should actually decorate strings
  56. * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
  57. */
  58. public function __construct($decorated = false, array $styles = array())
  59. {
  60. $this->decorated = (bool) $decorated;
  61. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  62. $this->setStyle('info', new OutputFormatterStyle('green'));
  63. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  64. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  65. foreach ($styles as $name => $style) {
  66. $this->setStyle($name, $style);
  67. }
  68. $this->styleStack = new OutputFormatterStyleStack();
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function setDecorated($decorated)
  74. {
  75. $this->decorated = (bool) $decorated;
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. public function isDecorated()
  81. {
  82. return $this->decorated;
  83. }
  84. /**
  85. * {@inheritdoc}
  86. */
  87. public function setStyle($name, OutputFormatterStyleInterface $style)
  88. {
  89. $this->styles[strtolower($name)] = $style;
  90. }
  91. /**
  92. * {@inheritdoc}
  93. */
  94. public function hasStyle($name)
  95. {
  96. return isset($this->styles[strtolower($name)]);
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function getStyle($name)
  102. {
  103. if (!$this->hasStyle($name)) {
  104. throw new InvalidArgumentException(sprintf('Undefined style: %s', $name));
  105. }
  106. return $this->styles[strtolower($name)];
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. public function format($message)
  112. {
  113. $message = (string) $message;
  114. $offset = 0;
  115. $output = '';
  116. $tagRegex = '[a-z][a-z0-9,_=;-]*+';
  117. preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, PREG_OFFSET_CAPTURE);
  118. foreach ($matches[0] as $i => $match) {
  119. $pos = $match[1];
  120. $text = $match[0];
  121. if (0 != $pos && '\\' == $message[$pos - 1]) {
  122. continue;
  123. }
  124. // add the text up to the next tag
  125. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset));
  126. $offset = $pos + strlen($text);
  127. // opening tag?
  128. if ($open = '/' != $text[1]) {
  129. $tag = $matches[1][$i][0];
  130. } else {
  131. $tag = isset($matches[3][$i][0]) ? $matches[3][$i][0] : '';
  132. }
  133. if (!$open && !$tag) {
  134. // </>
  135. $this->styleStack->pop();
  136. } elseif (false === $style = $this->createStyleFromString(strtolower($tag))) {
  137. $output .= $this->applyCurrentStyle($text);
  138. } elseif ($open) {
  139. $this->styleStack->push($style);
  140. } else {
  141. $this->styleStack->pop($style);
  142. }
  143. }
  144. $output .= $this->applyCurrentStyle(substr($message, $offset));
  145. if (false !== strpos($output, '<<')) {
  146. return strtr($output, array('\\<' => '<', '<<' => '\\'));
  147. }
  148. return str_replace('\\<', '<', $output);
  149. }
  150. /**
  151. * @return OutputFormatterStyleStack
  152. */
  153. public function getStyleStack()
  154. {
  155. return $this->styleStack;
  156. }
  157. /**
  158. * Tries to create new style instance from string.
  159. *
  160. * @param string $string
  161. *
  162. * @return OutputFormatterStyle|false false if string is not format string
  163. */
  164. private function createStyleFromString($string)
  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 false;
  171. }
  172. $style = new OutputFormatterStyle();
  173. foreach ($matches as $match) {
  174. array_shift($match);
  175. if ('fg' == $match[0]) {
  176. $style->setForeground($match[1]);
  177. } elseif ('bg' == $match[0]) {
  178. $style->setBackground($match[1]);
  179. } elseif ('options' === $match[0]) {
  180. preg_match_all('([^,;]+)', $match[1], $options);
  181. $options = array_shift($options);
  182. foreach ($options as $option) {
  183. try {
  184. $style->setOption($option);
  185. } catch (\InvalidArgumentException $e) {
  186. @trigger_error(sprintf('Unknown style options are deprecated since version 3.2 and will be removed in 4.0. Exception "%s".', $e->getMessage()), E_USER_DEPRECATED);
  187. return false;
  188. }
  189. }
  190. } else {
  191. return false;
  192. }
  193. }
  194. return $style;
  195. }
  196. /**
  197. * Applies current style from stack to text, if must be applied.
  198. *
  199. * @param string $text Input text
  200. *
  201. * @return string Styled text
  202. */
  203. private function applyCurrentStyle($text)
  204. {
  205. return $this->isDecorated() && strlen($text) > 0 ? $this->styleStack->getCurrent()->apply($text) : $text;
  206. }
  207. }