OutputFormatter.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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_replace("\0", '', $text);
  49. $text .= str_repeat("\0", $len - \strlen($text));
  50. }
  51. return $text;
  52. }
  53. /**
  54. * Initializes console output formatter.
  55. *
  56. * @param bool $decorated Whether this formatter should actually decorate strings
  57. * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
  58. */
  59. public function __construct($decorated = false, array $styles = array())
  60. {
  61. $this->decorated = (bool) $decorated;
  62. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  63. $this->setStyle('info', new OutputFormatterStyle('green'));
  64. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  65. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  66. foreach ($styles as $name => $style) {
  67. $this->setStyle($name, $style);
  68. }
  69. $this->styleStack = new OutputFormatterStyleStack();
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function setDecorated($decorated)
  75. {
  76. $this->decorated = (bool) $decorated;
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function isDecorated()
  82. {
  83. return $this->decorated;
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function setStyle($name, OutputFormatterStyleInterface $style)
  89. {
  90. $this->styles[strtolower($name)] = $style;
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. public function hasStyle($name)
  96. {
  97. return isset($this->styles[strtolower($name)]);
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function getStyle($name)
  103. {
  104. if (!$this->hasStyle($name)) {
  105. throw new InvalidArgumentException(sprintf('Undefined style: %s', $name));
  106. }
  107. return $this->styles[strtolower($name)];
  108. }
  109. /**
  110. * {@inheritdoc}
  111. */
  112. public function format($message)
  113. {
  114. $message = (string) $message;
  115. $offset = 0;
  116. $output = '';
  117. $tagRegex = '[a-z][a-z0-9_=;-]*+';
  118. preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, PREG_OFFSET_CAPTURE);
  119. foreach ($matches[0] as $i => $match) {
  120. $pos = $match[1];
  121. $text = $match[0];
  122. if (0 != $pos && '\\' == $message[$pos - 1]) {
  123. continue;
  124. }
  125. // add the text up to the next tag
  126. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset));
  127. $offset = $pos + \strlen($text);
  128. // opening tag?
  129. if ($open = '/' != $text[1]) {
  130. $tag = $matches[1][$i][0];
  131. } else {
  132. $tag = isset($matches[3][$i][0]) ? $matches[3][$i][0] : '';
  133. }
  134. if (!$open && !$tag) {
  135. // </>
  136. $this->styleStack->pop();
  137. } elseif (false === $style = $this->createStyleFromString(strtolower($tag))) {
  138. $output .= $this->applyCurrentStyle($text);
  139. } elseif ($open) {
  140. $this->styleStack->push($style);
  141. } else {
  142. $this->styleStack->pop($style);
  143. }
  144. }
  145. $output .= $this->applyCurrentStyle(substr($message, $offset));
  146. if (false !== strpos($output, "\0")) {
  147. return strtr($output, array("\0" => '\\', '\\<' => '<'));
  148. }
  149. return str_replace('\\<', '<', $output);
  150. }
  151. /**
  152. * @return OutputFormatterStyleStack
  153. */
  154. public function getStyleStack()
  155. {
  156. return $this->styleStack;
  157. }
  158. /**
  159. * Tries to create new style instance from string.
  160. *
  161. * @param string $string
  162. *
  163. * @return OutputFormatterStyle|false false if string is not format string
  164. */
  165. private function createStyleFromString($string)
  166. {
  167. if (isset($this->styles[$string])) {
  168. return $this->styles[$string];
  169. }
  170. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', strtolower($string), $matches, PREG_SET_ORDER)) {
  171. return false;
  172. }
  173. $style = new OutputFormatterStyle();
  174. foreach ($matches as $match) {
  175. array_shift($match);
  176. if ('fg' == $match[0]) {
  177. $style->setForeground($match[1]);
  178. } elseif ('bg' == $match[0]) {
  179. $style->setBackground($match[1]);
  180. } else {
  181. try {
  182. $style->setOption($match[1]);
  183. } catch (\InvalidArgumentException $e) {
  184. return false;
  185. }
  186. }
  187. }
  188. return $style;
  189. }
  190. /**
  191. * Applies current style from stack to text, if must be applied.
  192. *
  193. * @param string $text Input text
  194. *
  195. * @return string Styled text
  196. */
  197. private function applyCurrentStyle($text)
  198. {
  199. return $this->isDecorated() && \strlen($text) > 0 ? $this->styleStack->getCurrent()->apply($text) : $text;
  200. }
  201. }