SymfonyStyle.php 14 KB

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