SymfonyStyle.php 15 KB

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