SymfonyStyle.php 12 KB

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