SymfonyStyle.php 15 KB

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