SymfonyStyle.php 14 KB

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