SymfonyStyle.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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\Style;
  11. use Symfony\Component\Console\Exception\RuntimeException;
  12. use Symfony\Component\Console\Formatter\OutputFormatter;
  13. use Symfony\Component\Console\Helper\Helper;
  14. use Symfony\Component\Console\Helper\ProgressBar;
  15. use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
  16. use Symfony\Component\Console\Helper\Table;
  17. use Symfony\Component\Console\Input\InputInterface;
  18. use Symfony\Component\Console\Output\BufferedOutput;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. use Symfony\Component\Console\Question\ChoiceQuestion;
  21. use Symfony\Component\Console\Question\ConfirmationQuestion;
  22. use Symfony\Component\Console\Question\Question;
  23. use Symfony\Component\Console\Terminal;
  24. /**
  25. * Output decorator helpers for the Symfony Style Guide.
  26. *
  27. * @author Kevin Bond <kevinbond@gmail.com>
  28. */
  29. class SymfonyStyle extends OutputStyle
  30. {
  31. const MAX_LINE_LENGTH = 120;
  32. private $input;
  33. private $questionHelper;
  34. private $progressBar;
  35. private $lineLength;
  36. private $bufferedOutput;
  37. /**
  38. * @param InputInterface $input
  39. * @param OutputInterface $output
  40. */
  41. public function __construct(InputInterface $input, OutputInterface $output)
  42. {
  43. $this->input = $input;
  44. $this->bufferedOutput = new BufferedOutput($output->getVerbosity(), false, clone $output->getFormatter());
  45. // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.
  46. $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
  47. $this->lineLength = min($width - (int) (DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
  48. parent::__construct($output);
  49. }
  50. /**
  51. * Formats a message as a block of text.
  52. *
  53. * @param string|array $messages The message to write in the block
  54. * @param string|null $type The block type (added in [] on first line)
  55. * @param string|null $style The style to apply to the whole block
  56. * @param string $prefix The prefix for the block
  57. * @param bool $padding Whether to add vertical padding
  58. * @param bool $escape Whether to escape the message
  59. */
  60. public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = true)
  61. {
  62. $messages = is_array($messages) ? array_values($messages) : array($messages);
  63. $this->autoPrependBlock();
  64. $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
  65. $this->newLine();
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function title($message)
  71. {
  72. $this->autoPrependBlock();
  73. $this->writeln(array(
  74. sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  75. sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
  76. ));
  77. $this->newLine();
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function section($message)
  83. {
  84. $this->autoPrependBlock();
  85. $this->writeln(array(
  86. sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  87. sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
  88. ));
  89. $this->newLine();
  90. }
  91. /**
  92. * {@inheritdoc}
  93. */
  94. public function listing(array $elements)
  95. {
  96. $this->autoPrependText();
  97. $elements = array_map(function ($element) {
  98. return sprintf(' * %s', $element);
  99. }, $elements);
  100. $this->writeln($elements);
  101. $this->newLine();
  102. }
  103. /**
  104. * {@inheritdoc}
  105. */
  106. public function text($message)
  107. {
  108. $this->autoPrependText();
  109. $messages = is_array($message) ? array_values($message) : array($message);
  110. foreach ($messages as $message) {
  111. $this->writeln(sprintf(' %s', $message));
  112. }
  113. }
  114. /**
  115. * Formats a command comment.
  116. *
  117. * @param string|array $message
  118. */
  119. public function comment($message)
  120. {
  121. $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function success($message)
  127. {
  128. $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function error($message)
  134. {
  135. $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
  136. }
  137. /**
  138. * {@inheritdoc}
  139. */
  140. public function warning($message)
  141. {
  142. $this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
  143. }
  144. /**
  145. * {@inheritdoc}
  146. */
  147. public function note($message)
  148. {
  149. $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
  150. }
  151. /**
  152. * {@inheritdoc}
  153. */
  154. public function caution($message)
  155. {
  156. $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
  157. }
  158. /**
  159. * {@inheritdoc}
  160. */
  161. public function table(array $headers, array $rows)
  162. {
  163. $style = clone Table::getStyleDefinition('symfony-style-guide');
  164. $style->setCellHeaderFormat('<info>%s</info>');
  165. $table = new Table($this);
  166. $table->setHeaders($headers);
  167. $table->setRows($rows);
  168. $table->setStyle($style);
  169. $table->render();
  170. $this->newLine();
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function ask($question, $default = null, $validator = null)
  176. {
  177. $question = new Question($question, $default);
  178. $question->setValidator($validator);
  179. return $this->askQuestion($question);
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. public function askHidden($question, $validator = null)
  185. {
  186. $question = new Question($question);
  187. $question->setHidden(true);
  188. $question->setValidator($validator);
  189. return $this->askQuestion($question);
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function confirm($question, $default = true)
  195. {
  196. return $this->askQuestion(new ConfirmationQuestion($question, $default));
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function choice($question, array $choices, $default = null)
  202. {
  203. if (null !== $default) {
  204. $values = array_flip($choices);
  205. $default = $values[$default];
  206. }
  207. return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
  208. }
  209. /**
  210. * {@inheritdoc}
  211. */
  212. public function progressStart($max = 0)
  213. {
  214. $this->progressBar = $this->createProgressBar($max);
  215. $this->progressBar->start();
  216. }
  217. /**
  218. * {@inheritdoc}
  219. */
  220. public function progressAdvance($step = 1)
  221. {
  222. $this->getProgressBar()->advance($step);
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function progressFinish()
  228. {
  229. $this->getProgressBar()->finish();
  230. $this->newLine(2);
  231. $this->progressBar = null;
  232. }
  233. /**
  234. * {@inheritdoc}
  235. */
  236. public function createProgressBar($max = 0)
  237. {
  238. $progressBar = parent::createProgressBar($max);
  239. if ('\\' !== DIRECTORY_SEPARATOR) {
  240. $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591
  241. $progressBar->setProgressCharacter('');
  242. $progressBar->setBarCharacter('▓'); // dark shade character \u2593
  243. }
  244. return $progressBar;
  245. }
  246. /**
  247. * @param Question $question
  248. *
  249. * @return string
  250. */
  251. public function askQuestion(Question $question)
  252. {
  253. if ($this->input->isInteractive()) {
  254. $this->autoPrependBlock();
  255. }
  256. if (!$this->questionHelper) {
  257. $this->questionHelper = new SymfonyQuestionHelper();
  258. }
  259. $answer = $this->questionHelper->ask($this->input, $this, $question);
  260. if ($this->input->isInteractive()) {
  261. $this->newLine();
  262. $this->bufferedOutput->write("\n");
  263. }
  264. return $answer;
  265. }
  266. /**
  267. * {@inheritdoc}
  268. */
  269. public function writeln($messages, $type = self::OUTPUT_NORMAL)
  270. {
  271. parent::writeln($messages, $type);
  272. $this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
  273. }
  274. /**
  275. * {@inheritdoc}
  276. */
  277. public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
  278. {
  279. parent::write($messages, $newline, $type);
  280. $this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
  281. }
  282. /**
  283. * {@inheritdoc}
  284. */
  285. public function newLine($count = 1)
  286. {
  287. parent::newLine($count);
  288. $this->bufferedOutput->write(str_repeat("\n", $count));
  289. }
  290. /**
  291. * Returns a new instance which makes use of stderr if available.
  292. *
  293. * @return self
  294. */
  295. public function getErrorStyle()
  296. {
  297. return new self($this->input, $this->getErrorOutput());
  298. }
  299. /**
  300. * @return ProgressBar
  301. */
  302. private function getProgressBar()
  303. {
  304. if (!$this->progressBar) {
  305. throw new RuntimeException('The ProgressBar is not started.');
  306. }
  307. return $this->progressBar;
  308. }
  309. private function autoPrependBlock()
  310. {
  311. $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
  312. if (!isset($chars[0])) {
  313. return $this->newLine(); //empty history, so we should start with a new line.
  314. }
  315. //Prepend new line for each non LF chars (This means no blank line was output before)
  316. $this->newLine(2 - substr_count($chars, "\n"));
  317. }
  318. private function autoPrependText()
  319. {
  320. $fetched = $this->bufferedOutput->fetch();
  321. //Prepend new line if last char isn't EOL:
  322. if ("\n" !== substr($fetched, -1)) {
  323. $this->newLine();
  324. }
  325. }
  326. private function reduceBuffer($messages)
  327. {
  328. // We need to know if the two last chars are PHP_EOL
  329. // Preserve the last 4 chars inserted (PHP_EOL on windows is two chars) in the history buffer
  330. return array_map(function ($value) {
  331. return substr($value, -4);
  332. }, array_merge(array($this->bufferedOutput->fetch()), (array) $messages));
  333. }
  334. private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
  335. {
  336. $indentLength = 0;
  337. $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
  338. $lines = array();
  339. if (null !== $type) {
  340. $type = sprintf('[%s] ', $type);
  341. $indentLength = strlen($type);
  342. $lineIndentation = str_repeat(' ', $indentLength);
  343. }
  344. // wrap and add newlines for each element
  345. foreach ($messages as $key => $message) {
  346. if ($escape) {
  347. $message = OutputFormatter::escape($message);
  348. }
  349. $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true)));
  350. if (count($messages) > 1 && $key < count($messages) - 1) {
  351. $lines[] = '';
  352. }
  353. }
  354. $firstLineIndex = 0;
  355. if ($padding && $this->isDecorated()) {
  356. $firstLineIndex = 1;
  357. array_unshift($lines, '');
  358. $lines[] = '';
  359. }
  360. foreach ($lines as $i => &$line) {
  361. if (null !== $type) {
  362. $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
  363. }
  364. $line = $prefix.$line;
  365. $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
  366. if ($style) {
  367. $line = sprintf('<%s>%s</>', $style, $line);
  368. }
  369. }
  370. return $lines;
  371. }
  372. }